使用this.refs的弃用警告

dj2*_*017 38 javascript 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,
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

这个问题是ESLint不断告诉我"this.refs"已经折旧了.

我该怎么做?如何修复它以便不使用折旧代码?

Chr*_*ris 44

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

"Using string literals in ref attributes is deprecated (react/no-string-refs)"
Run Code Online (Sandbox Code Playgroud)

您收到此警告是因为已实现了不推荐使用的方式refs(通过使用字符串).根据您的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>
  );
}
Run Code Online (Sandbox Code Playgroud)

反应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>
  );
}
Run Code Online (Sandbox Code Playgroud)

为了更好的可读性,您还可以:

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

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

旧版API:字符串引用

如果您以前使用过React,那么您可能熟悉旧的API,其中ref属性是字符串 "textInput",并且DOM节点被访问为this.refs.textInput.我们建议不要使用它,因为字符串引用有一些问题,被认为是遗留问题,很可能会在未来的某个版本中删除.如果您当前正在使用this.refs.textInput访问refs,我们建议使用回调模式.