小编典典

使用this.refs的弃用警告

reactjs

我有一个React组件,我想在单击时切换一个CSS类。

所以我有这个:

export class myComponent extends React.Component {
  constructor() {
    super();
    this.state = { clicked: false };
    this.handleClick = this.handleClick.bind(this);
  }

  render() {
    return (
      <div>
        <div onClick={this.clicked}><span ref="btn" className="glyphicon">&nbsp;</span></div>
      </div>
    );
  }

  handleClick() {
    this.refs.btn.classList.toggle('active');
  }

  componentDidMount() {
    this.refs.btn.addEventListener('click', this.handleClick);
    this.setState({
      clicked: this.state.clicked = true,
    });
  }

  componentWillUnmount() {
    this.refs.btn.removeEventListener('click', this.handleClick);
    this.setState({
      clicked: this.state.clicked = false,
    });
  }
}

这个问题是ESLint不断告诉我“ this.refs”已贬值。

我该怎么办?我如何解决它而不使用折旧的代码?


阅读 4805

收藏
2020-07-22

共1个答案

小编典典

您要引用的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访问引用,则建议使用回调模式。

2020-07-22