我有一个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”已贬值。

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

最佳答案

您所引用的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 and the DOM的内容,尤其是this section:

关于javascript - 使用this.refs的弃用警告,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43873511/

10-12 23:36