Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

react中为什么方法需要bind #44

Open
bibi7 opened this issue Nov 5, 2019 · 0 comments
Open

react中为什么方法需要bind #44

bibi7 opened this issue Nov 5, 2019 · 0 comments
Labels

Comments

@bibi7
Copy link
Owner

bibi7 commented Nov 5, 2019

其实看官方文档的时候,文档也会这么建议:

You have to be careful about the meaning of this in JSX callbacks. In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.

由于js特殊的机制原因,this往往是在运行时决定的。不同的调用环境决定了不同的this指向。render中传进去的事件往往作为回调。所以回调函数被触发的时候this指向的是window对象,并不是指向这个组件。bind是为了重新将this绑定到组件上。
具体可读SyntheticEvent

所以也就有文档推荐的两种做法:

class LoggingButton extends React.Component {
  // This syntax ensures `this` is bound within handleClick.
  // Warning: this is *experimental* syntax.
  handleClick = () => {
    console.log('this is:', this);
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }
}
class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }

  render() {
    // This syntax ensures `this` is bound within handleClick
    return (
      <button onClick={(e) => this.handleClick(e)}>
        Click me
      </button>
    );
  }
}
@bibi7 bibi7 added the react label Nov 5, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant