我有4个特定React类的实例.在componentDidMount()我想存储每个实例的y位置之后.
如何处理渲染元素?我不能使用classname,因为我有4个具有不同位置的同一个类的元素.
我的ReactJS组件:
const Col = React.createClass({
componentDidMount: function() {
//here address the actual rendered col-instance
},
render() {
return (
<div className='col'>
</div>
);
}
});
Run Code Online (Sandbox Code Playgroud)
Kal*_*sev 11
使用refs.
首先,ref在每个JSX cols元素上连接一个属性.然后,ref在componentDidMount方法内部使用它来访问组件的DOM节点(实际的HTMLElement).最后,获取元素的位置/偏移量或您需要的任何其他内容.
const Col = React.createClass({
componentDidMount: function() {
// this.refs.col1 is the actual DOM element,
// so you can access it's position / offset or whatever
const offsetTop = this.refs.col1.offsetTop;
},
render() {
return (
<div className="col" ref="col1">
</div>
);
}
});
Run Code Online (Sandbox Code Playgroud)
PS:我不确定你说元素y位置是什么意思.无论如何,一旦你知道如何获得DOM元素(this.refs.col1),你就可以使用javascript来检索你需要的位置.
| 归档时间: |
|
| 查看次数: |
7213 次 |
| 最近记录: |