【react】事件绑定与传参

class中的方法默认不会绑定this,所以如果事件处理函数中使用到了this,必须手动绑定this。官方介绍了四种方法:

第一种 在构造函数中绑定

  • 优点:性能较好,只生成一个方法实例,
  • 缺点:不能携带参数,需要增加额外的代码
class LoggingButton extends React.Component {
  constructor(props){
    super(props)
    this.state={}
  
    this.handleClick=this.handleClick.bind(this)
  }
  handleClick (){
    ...
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }
}
复制代码

第二种 调用时绑定

  • 优点:可携带参数,无需额外代码,
  • 缺点:每次调用都会生成一个新的方法实例,性能不好
class LoggingButton extends React.Component {
  constructor(props){
    super(props)
    this.state={}
  }
  handleClick (val){
    ...
  }

  render() {
    return (
      <button onClick={this.handleClick.bind(this,'a')}>
        Click me
      </button>
    );
  }
}
复制代码

第三种 用箭头函数调用(箭头函数的this指向定义该函数时所在的作用域指向的对象)

  • 优缺点同第二种方式
class LoggingButton extends React.Component {
  constructor(props){
    super(props)
    this.state={}
  }
  handleClick (val,e){
    ...
  }

  render() {
    return (
      <button onClick={(e)=>this.handleClick('a',e)}>
        Click me
      </button>
    );
  }
}
复制代码

第四种 方法用箭头函数声明

  • 优点:性能好,无需额外代码,只生成一个实例
  • 缺点:不能携带额外参数
class LoggingButton extends React.Component {
  constructor(props){
    super(props)
    this.state={}
  }
  handleClick= (val) => {
    ...
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }
}
复制代码

说明1

若要携带event外的参数,只能使用第二种和第三种方式

说明2

若未绑定this,直接onClick={this.test()}这样使用,则该事件只会在初始渲染时触发,点击不会触发。完整代码如下:

class LoggingButton extends React.Component {
  handleClick (){
    ...
  }

  render() {
    return (
      <button onClick={this.handleClick()}>
        Click me
      </button>
    );
  }
}
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享