在实际 DOM 可用之前调用的 componentDidMount

componentDidMount called before real DOM is available

我是 React 的新手。我需要获取元素的高度,所以我试图在 componentDidMount 方法中获取它。我明白这个方法是在渲染组件之后调用的,这是在最后编写我假设的真实 DOM 。但是,componentDidMount 在最终 DOM 可用之前被调用。怎么会?

componentDidMount() {
  const el = window.document.getElementById('comments'); // el is null
  console.log(el);  
}

resize() {
  const el = window.document.getElementById('comments'); // el is null
  console.log(el);
}

render() {
  const { name } = this.props;
  const Comments = this.props.comments.filter(comment => comment.body !== null && comment.body !== '').map(comment => <Comment key={comment.id} comment={comment} />);
  return (
    <div ref={this.resize}>
      <div>
        <div id="comments">
          { Comments }
        </div>
      </div>
    </div>
  );
}

在 React 上,您不应依赖 render 方法返回的 DOM。组件和渲染部分是 React 中的 2 个不同进程,因此从外到内的方法在 React 中不起作用。您可以做的是,将评论保存为参考:

 componentDidMount() {
      var erd = elementResizeDetectorMaker();
      erd.listenTo(this.refs.comments, resize);
    }

    resize(element) {
       //do-some-thing
    }

    render() {
      const { name } = this.props;
      const Comments = this.props.comments.filter(comment => comment.body !== null && comment.body !== '').map(comment => <Comment key={comment.id} comment={comment} />);
      return (
        <div>
          <div>
            <div ref={comments => { this.comments = comments; }}>
              { Comments }
            </div>
          </div>
        </div>
      );

}

PS:在类似的情况下,我使用了这个神奇的库:https://github.com/wnr/element-resize-detector

你的select或const el = window.document.getElementById('comments');(这是反模式) 为空,因为您的 select 节点在 componentDidiMount 渲染生命周期中不存在。

您需要 select 您节点的内部 React 模式(或影子 DOM)。

更改此代码块的代码,将 javascript select 或 'getElementBy' 替换为 React 的引用。检查文档 https://facebook.github.io/react/docs/refs-and-the-dom.html

componentDidMount() {
  let el = this.refs['comments']
  console.log(el.clientHeight)
  this.resize()
}

resize() {
  let el = this.refs['comments']
  console.log(el.clientHeight)
}

render() {
  const { name } = this.props;
  const Comments = this.props.comments.filter(comment => comment.body !== null && comment.body !== '').map(comment => <Comment key={comment.id} comment={comment} />);
  return (
    <div ref='comments'>
      <div>
        <div id="comments">
          { Comments }
        </div>
      </div>
    </div>
  );
}