最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【基本解决】ReactJS中bind函数bind()的含义

ReactJS crifan 3804浏览 0评论

Handling Events – React

->

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};
    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }
  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? ‘ON’ : ‘OFF’}
      </button>
    );
  }
}
ReactDOM.render(
  <Toggle />,
  document.getElementById(‘root’)
);

Function.prototype.bind() – JavaScript | MDN

然后看到中文解释:

处理事件 – React 中文文档

在JSX回调中你必须注意 this 的指向。 在 JavaScript 中,类方法默认没有 绑定 的。如果你忘记绑定 this.handleClick 并将其传递给onClick,那么在直接调用该函数时,this 会是 undefined 。

这不是 React 特有的行为;这是 JavaScript 中的函数如何工作的一部分。 一般情况下,如果你引用一个后面没跟 () 的方法,例如 onClick={this.handleClick} ,那你就应该 绑定(bind) 该方法。

【总结】

貌似懂了。但是不全懂。总之就是:

如果后面要调用到this.handleClick:

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? ‘ON’ : ‘OFF’}
      </button>
    );
  }

最好用ReactJS中推荐的:

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};
    // 这个绑定是必要的,使`this`在回调中起作用
    this.handleClick = this.handleClick.bind(this);
  }

写就好了。

【后记】

后来有点明白了:

此处的bind(this),主要的作用就是:

被绑定的函数内部,如果使用this,就可以识别是当前类(或Component)的实例了。

否则没有bind(this)的话,this.setState之类的函数,就无法识别了。

转载请注明:在路上 » 【基本解决】ReactJS中bind函数bind()的含义

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
89 queries in 0.167 seconds, using 22.14MB memory