我是 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
关于javascript - 在真正的 DOM 可用之前调用 componentDidMount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43077602/