[英]How to get returned div's offset/position in react?
在我的代码返回中,我有:
return (
<div className="pos__container" >
<div className="pos__container--line" ></div>
{timeList}
</div>
);
<div className="pos__container--line">
margin-left:10%;
其他样式无关紧要。
在构造函数下的函数中,我想获取其位置。
要获取偏移量,我需要先获取div。
我已经尝试过:const element = ReactDOM.findDOMNode(this); findDOMNode was called on an unmounted component.
返回findDOMNode was called on an unmounted component.
还尝试使用document.QuerySelector(“。pos__container--line”); 返回null
感觉像我没有选择。
关于如何正确执行此操作的任何建议或其他任何执行方法?
任何帮助,将不胜感激。
提前致谢!
首先,您需要向您感兴趣的元素添加一个引用 :
return (
<div className="pos__container" >
<div className="pos__container--line" ref={el => this.containerLine = el} ></div>
{timeList}
</div>
);
然后,您可以在渲染组件后访问该引用:
componentDidMount() {
// it is a regular DOM node
this.containerLine.offsetTop
// or with jquery
$(this.containerLine).offset()
}
您需要使用React的生命周期方法,该方法在组件安装后被调用。
componentDidMount(){
var node = ReactDOM.findDOMNode(this);
console.log(window.getComputedStyle(node).offset);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.