我想知道从同一组件访问渲染函数内部的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> ) })
在这里,无需使用setTimeout。有一些组件的生命周期方法,其中的方法componentDidMount在渲染之后被调用。因此,您可以在该方法中获取对div的引用。
componentDidMount
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> ); });