2016-12-30 51 views
4

我有一个特定的React-class的4个实例。 componentDidMount()后我想存储每个实例的y位置。如何获取componentDidMount()中的ReactJS元素?

我该如何解决呈现的元素?我不能使用classname,因为我有4个具有不同位置的同一个类的元素。

我ReactJS组件:

const Col = React.createClass({ 
    componentDidMount: function() { 
     //here address the actual rendered col-instance 
    }, 

    render() { 
     return (
      <div className='col'> 
      </div> 
     ); 
    } 
}); 
+0

只是试图了解更多的问题。你是否试图存储每个React组件实例的y位置以便稍后使用?安装后每个元件的y位置也会发生变化吗? – HussienK

+0

我需要存储它,它不会改变。也许我可以使用this.ref? – vuvu

+1

你能否解释一下你想要达到的目标?你想在哪里存储什么?你想如何访问存储的值和从哪里? –

回答

5

使用refs

首先,在每个JSX cols元素上挂接一个ref属性。然后,在componentDidMount方法中使用此ref来访问组件的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> 
     ); 
    } 
}); 

PS:我不确定你说的元素y的位置是什么意思。无论如何,一旦你知道如何获得DOM元素(this.refs.col1),那么你可以使用你需要的javascript to retrieve the position

+1

对于React.js的旧版API来说,这是一个很好的解决方案。从https://reactjs.org/docs/refs-and-the-dom.html:“我们建议不要这样做,因为字符串引用有一些问题,被认为是遗留问题,并且可能会在将来的某个版本中删除。 “用新的API这里的解决方案:https://stackoverflow.com/questions/42242146/react-how-to-access-the-dom-element-in-my-render-function-from-the-same-compone – favero