react.js - React ref不能写在render之外的地方,那有这种需求的时候怎么办?
本文介绍了react.js - 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>
)
}
})
解决方案
组件不要直接保存在state里就可以啦
var Father = React.createClass({
getInitalState:function(){
return {
children:[]
}
},
handleClick:function(){
var childrenTemp = this.state.children;
this.setState({
children : childrenTemp.push({id : 'id'})
})
},
render:function(){
var childrenTemp = this.state.children;
return (
<div>
{
childrenTemp.map(function(item, index){
return <Child key={index} ref={item.id}>
})
}
</div>
)
}
});
这篇关于react.js - React ref不能写在render之外的地方,那有这种需求的时候怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文