React ref不能写在render之外的地方,那有这种需求的时候怎么办
展开全部
例如点击按钮就新增一个子组件,同时需要使用ref引用子组件,我像下面这样把ref写在handleClick里面时,因为不在render里面,会报错:addComponentAsRefTo(...): Only a ReactOwner can have refs.
var Father = React.createClass({
getInitalState:function(){
return {children:[]}
},
handleClick:function(){
var childrenTemp = this.state.children
this.setState{children:childrenTemp.push(<Child ref="childRef">)}
},
render:function(){
return (
<div>{this.state.children}</div>
)
}
})
var Father = React.createClass({
getInitalState:function(){
return {children:[]}
},
handleClick:function(){
var childrenTemp = this.state.children
this.setState{children:childrenTemp.push(<Child ref="childRef">)}
},
render:function(){
return (
<div>{this.state.children}</div>
)
}
})
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询