javascript - 带有 "this"关键字的 React 类行为

标签 javascript reactjs react-native

为什么我需要在 onChange 处理程序中为 handleChange 添加 bind(this) 以获得正确的 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 语法,他们在组件创建时删除了自动绑定(bind),就像在旧的 .createClass 语法中一样。默认情况下,使用 es2015 中的 class 语法,你必须将 this 绑定(bind)到一个方法才能使用 this 类,所以这里也是如此。

您可以在 this changelog 中阅读 React 做出此更改的决定。博文。

关于javascript - 带有 "this"关键字的 React 类行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35875132/

相关文章:

javascript - Node.js 流 'end' 事件未触发

javascript - 舍入到最接近的十的幂

javascript - 自动完成从 API 获取数据

javascript - React Native Android 中 View 之间的导航示例?

ios - 不变违规 : Native component for "RNSVGSvgView" does not exist

javascript - react 父/子状态变化设计问题

javascript - 使用 javascript 读取属性文件

javascript - 在 JavaScript 中使用 var 关键字在函数外部声明变量

javascript - React Router 和任意查询参数 : Page Refreshes Unintentionally on Load?

javascript - React 如何使用模式关闭弹出窗口