React,如何从同一个组件访问我的渲染函数中的DOM元素

won*_*nry 23 javascript css jsx reactjs

我想知道从同一个组件访问我的渲染函数中的DOM元素的最佳实践是什么.请注意,我将在页面上多次渲染此组件.

例如

var TodoItem = React.createClass({
    ...
    render:function(){

        function oneSecLater(){
            setTimeout(function(){
            //select the current className? this doesn't work, but it gives you an idea what I want.
            document.getElementsByClassName('name').style.backgroundColor = "red";
                )}, 1000);
        }

        return(
            <div className='name'>{this.oneSecLater}</div>
        )



})
Run Code Online (Sandbox Code Playgroud)

VJA*_*JAI 22

您可以使用它ReactDOM.findDOMNode(this)来访问底层DOM节点.但访问DOM节点并像操作一样操作是违反React编程风格的.最好使用状态变量并调用该setState方法来重新呈现DOM.


Sab*_*san 16

在这里,不需要使用setTimeout.组件有生命周期方法,componentDidMount在渲染后调用.因此,您可以在方法中获得对div的引用.

var TodoItem = React.createClass({
  ...
  componentDidMount: function () {
     if(this.myDiv) {
        this.myDiv.style.backgroundColor = "red";
     }
  }
  render:function(){
    return(
        <div className='name' ref = {c => this.myDiv = c}></div>
    );
});
Run Code Online (Sandbox Code Playgroud)

  • 似乎在最近版本的React中,他们建议使用React.createRef()而不是回调api。https://reactjs.org/docs/refs-and-the-dom.html#creating-refs (3认同)