使用“this”关键字响应类行为

React Class behaviour with "this" keyword

本文关键字:响应 关键字 this 使用      更新时间:2023-09-26

为什么我需要在onChange处理程序中添加bind(this) for handleChange才能获得正确的this关键字?

class SearchBar extends React.Component{
  constructor(props){
    super(props);
  }
  handleChange(){
    console.log(this)
    this.props.onUserInput(
      this.refs.filterTextInput.value,
      this.refs.inStockOnlyInput.checked
    );
  }
  render() {
    return (
      <form>
        <input
          type="text"
          placeholder="Searrch...." 
          value={this.props.filterText}
          ref="filterTextInput"
          onChange={this.handleChange.bind(this)} // the bind(this) is needed if not this in handleChange became undefined
        />
        <p>
          <input
            type="checkbox"
            checked={this.props.inStockOnly}
            ref="inStockOnlyInput"
            onChange={this.handleChange}
          />
          {' '}
          only show products in stock
        </p>
      </form>
    );
  }
}

这是因为使用新的 React extends Component 语法,他们在组件创建时删除了自动绑定,就像他们在旧的.createClass语法中一样。默认情况下,使用 es2015 中的类语法,您必须将其绑定到方法才能使用类 this,因此此处也是如此。

您可以在这篇更新日志博客文章中阅读有关 React 做出此更改的决定。