React报错: Warning: A string ref, “title”, has been found within a strict mode tree. String refs are a source of potential bugs and should be avoided. We recommend using useRef() or createRef() instead. Learn more about using refs safely here:
官方提示在以后的更新中,可能不再使用ref来进行dom渲染,建议使用这种方法:
案例:
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
实际应用测试:
constructor(props) {
super(props);
this.state = {
list:[]
};
this.title = React.createRef();
}
addData=(e)=>{
//按下回车的时候在增加
// eslint-disable-next-line eqeqeq
if(e.keyCode==13){
// alert(title);
let title=this.title.current.value;
let tempList=this.state.list;
tempList.push({
title:title,
checked:false
})
//改变后的值赋值给list
this.setState({
list:tempList
})
//表单置为空
this.title.current.value='';
//调用方法 this.title.current.方法名()
}
}
render(){
return(
<div>
<input ref="title" onKeyUp={this.addData} />
</div>
)
}
官方给出的解释大意是:避免refs过度使用。
原话:你可能首先会想到使用 refs 在你的 app 中“让事情发生”。如果是这种情况,请花一点时间,认真再考虑一下 state 属性应该被安排在哪个组件层中。通常你会想明白,让更高的组件层级拥有这个 state,是更恰当的。查看 状态提升 以获取更多有关示例。