react创建的组件中bind的使用

发布时间:2019-06-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了react创建的组件中bind的使用脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
export class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {count: props.initialCount};
    this.tick = this.tick.bind(this);
  }
  tick() {
    this.setState({count: this.state.count + @H_126_38@1});
  }
  render() {
    return (
      <div onClick={this.tick}>
        Clicks: {this.state.count}
      </div>
    );
  }
}
Counter.propTypes = { initialCount: React.PropTypes.number };
Counter.defaultProps = { initialCount: 0 };

Methods follow the same SEMantics as regular ES6 classes, meaning that they don't automatically bind this to the instance. You'll have to explicitly use .bind(this) or arrow functions =>:

// You can use bind() to preserve `this`
<div onClick={this.tick.bind(this)}>

// Or you can use arrow functions
<div onClick={() => this.tick()}>

这是react官网上面的例子,也就是说,如果我们使用了es6(这里应该指的是使用的时候采用es6,而不是定义的时候采用es6)的=>,就可以不用bind绑定this,因为es6中this是自动绑定到组件上去的。

脚本宝典总结

以上是脚本宝典为你收集整理的react创建的组件中bind的使用全部内容,希望文章能够帮你解决react创建的组件中bind的使用所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。