react中的属性初始化器、箭头函数、bind绑定函数的区别

版权声明:转载请注明作者(独孤尚良dugushangliang)出处: https://blog.csdn.net/dugushangliang/article/details/90580582

 

参阅https://www.runoob.com/react/react-event-handle.html

这里的属性初始化器,指的是,handleClick在类中是一个属性,这个属性指的是一个函数。

(本处是个人猜测,未找到可靠资料证实,若有发现或异议请提出)

//handleClick使用属性初始化器语法
class LoggingButton extends React.Component {
  // 这个语法确保了 `this` 绑定在  handleClick 中
  // 这里只是一个测试
  handleClick = () => {
    console.log('this is:', this);
  }
 
  render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }
}

 这里的绑定,值得是,在render的jsx中,<button>的onClick会调用handleClick方法,但函数/方法在JavaScript是一等公民,所以直接调用,这个this在严格模式下是无所指的,在不严格的情况下是windows,并不是我们创建的这个类的实例。那怎么让这个函数被这个实例所用呢?用bind绑定。注意:这只是绑定,并没有执行这个函数。

//handleClick使用bind绑定函数
class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};
 
    // 这边绑定是必要的,这样 `this` 才能在回调函数中使用
    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('example')
);

 下面的这个箭头函数,指的是,每次点击这个button后,根据onClick,会生成一个箭头函数,这个箭头函数返回 this.handleClick(e),箭头函数的this指的是当前的this(this这个在JavaScript是玄之又玄,不好参悟的,需要多次揣摩其精髓……)。

//handleClick使用箭头函数
class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }
 
  render() {
    //  这个语法确保了 `this` 绑定在  handleClick 中
    return (
      <button onClick={(e) => this.handleClick(e)}>
        Click me
      </button>
    );
  }
}

上面三种,都可以实现button的点击触发效果,但是箭头函数因为每次调用都要重新生成一个函数,开销较大,而前两者是对同一个函数的反复调用。所以在选择上,各位酌情处置。

 

独孤尚良dugushangliang——著

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值