A string ref, “title“, has been found within a strict mode tree. String refs are a source of po

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,是更恰当的。查看 状态提升 以获取更多有关示例。

官方给出解释的链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值