如何在componentDidMount()中获取ReactJS元素?

vuv*_*uvu 6 reactjs

我有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元素上连接一个属性.然后,refcomponentDidMount方法内部使用它来访问组件的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来检索你需要的位置.

  • 对于React.js的旧API来说,这是一个很好的解决方案.从https://reactjs.org/docs/refs-and-the-dom.html:"我们反对这样做,因为串裁判有一些问题,被认为是传统的,并有可能在未来的版本中的一个将被删除. "使用新API解决方案:/sf/ask/2956950251/ (2认同)