【问题标题】:Ref current is null参考电流为空
【发布时间】:2020-01-06 23:41:20
【问题描述】:

当调用调整大小事件时,我正在记录 ref 的当前值。当窗口调整大小时,参考的电流为空。

class Popout extends React.PureComponent {

  constructor(props) {
    super(props)
    this.popoutRef = React.createRef() // current = null
  }

  isWithinViewPort = () => {
    console.log('popoutRef', this.popoutRef)
  }

  componentDidMount() {
    window.addEventListener('resize', this.isWithinViewPort)
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.isWithinViewPort)
  }

  render() {
    const { id, children, borderColor, style, hidden, pointerLeft, pointerRight } = this.props

    if (hidden) {
      return null
    }

    return (
      <div id={id} className="popout" style={style} ref={this.popoutRef}>
        {children}
      </div>
    )
  }
}

Here's codesandbox link 代码在./components/Popout.js 第 46 行下。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    你有什么问题?

    ref 仅在您的组件已安装和渲染时才设置。你的render 方法有这个条件:

    if (hidden) {
      return null
    }
    

    这意味着,如果 Popout 被隐藏,则不会有 ref。

    【讨论】:

      猜你喜欢
      • 2020-09-11
      • 2019-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-24
      • 2020-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多