栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用this.refs的弃用警告

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用this.refs的弃用警告

您要引用的Lint规则称为 no-string-refs, 并通过以下方式警告您:

"Using string literals in ref attributes is deprecated (react/no-string-refs)"

之所以收到此警告,是因为已实现了不赞成使用的使用方式

refs
(通过使用字符串)。根据您的React版本,您可以执行以下操作:

React 16.3及更高版本

constructor() {  super();  this.btnRef= React.createRef();  this.state = { clicked: false };  this.handleClick = this.handleClick.bind(this);}render() {  return (    <div>      <div onClick={this.addVote}><span ref={this.btnRef} className="glyphicon">&nbsp;</span></div>    </div>  );}

React 16.2及更早版本

constructor() {  super();  this.btnRef;  //not necessary to declare the variable here, but I like to make it more visible.  this.state = { clicked: false };  this.handleClick = this.handleClick.bind(this);}render() {  return (    <div>      <div onClick={this.addVote}><span ref={(el) => this.btnRef = el} className="glyphicon">&nbsp;</span></div>    </div>  );}

为了获得更好的可读性,您还可以执行以下操作:

render() {  let myRef = (el) => this.btnRef = el;  return (    <div>      <div onClick={this.addVote}><span ref={myRef} className="glyphicon">&nbsp;</span></div>    </div>  );}

看一下官方文档中关于 Refs和DOM的内容 ,特别是本节内容:

旧版API:字符串引用

如果您之前使用过React,那么您可能会熟悉一个较旧的API,该API的

ref
属性是一个字符串,例如
"textInput"
,并且DOM节点的访问方式是
this.refs.textInput
。我们建议不要这样做,因为字符串引用存在一些问题,被认为是旧问题,并且
很可能会在将来的发行版中删除 。如果您当前正在使用
this.refs.textInput
访问引用,则建议使用回调模式。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/418019.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号