首页 > 解决方案 > 请求解释 React 中“将事件处理程序绑定到类实例”的概念

问题描述

嗨,我是全栈 Web 开发的新手,我正在尝试理解React 中的“将事件处理程序绑定到类实例”的概念

class Foo extends React.Component{
  constructor( props ){
    super( props );
    this.handleClick = this.handleClick.bind(this); // <- why?
  }
  
  handleClick(event){
    // your event handling logic
  }
  
  render(){
    return (
      <button type="button" 
      onClick={this.handleClick}>
      Click Me
      </button>
    );
  }
}

ReactDOM.render(
  <Foo />,
  document.getElementById("app")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="app"></div>

标签: javascriptreactjsclassbindingevent-handling

解决方案


反应文档https://reactjs.org/docs/handling-events.html

您必须小心 JSX 回调中 this 的含义。在 JavaScript 中,默认情况下不绑定类方法。如果您忘记绑定 this.handleClick 并将其传递给 onClick,则在实际调用该函数时 this 将是未定义的。

这不是 React 特有的行为;它是 JavaScript 中函数工作方式的一部分。一般情况下,如果引用的方法后面不带 (),比如onClick={this.handleClick},则应该绑定该方法。

class Foo extends React.Component{
  constructor( props ){
    super( props );
  }
    
  handleClick(event){
    console.log(this); // 'this' is undefined
  }
    
  render(){
    return (
      <button type="button" onClick={this.handleClick}>
        Click Me
      </button>
    );
  }
}

ReactDOM.render(
  <Foo />,
  document.getElementById("app")
);

要解决,您可以绑定this到类构造函数上的函数

  constructor( props ){
    super( props );
    this.handleClick = this.handleClick.bind(this); 
  }

或公共类字段语法(箭头函数)

class Foo extends React.Component{
  handleClick = () => {
    console.log(this); 
  }
 
  render(){
    return (
      <button type="button" onClick={this.handleClick}>
        Click Me
      </button>
    );
  }
} 

推荐阅读