react事件处理,为类方法绑定this

  • react事件绑定属性的命名采用驼峰命名法,
  • 如果采用JSX的语法,需要传入一个函数作为事件处理函数,而不是一个字符串(DOM元素的写法)。

阻止事件的默认行为:

  • 不能使用返回false的方式来阻止默认行为,必须明确的使用preventDefault

在类方法中绑定this

注:要谨慎的在类方法中使用this,因为类方法默认不会绑定this。需要主动的将这类方法绑定到this上。

为类方法上绑定this的方法:

  • 在构造方法中为类方法绑定this
class LoggingButton extends React.Component {
  constructor(props){
		super(props);
		
		//类方法,必须为每个类方法绑定this,否则在类方法总使用this时,会是undefined
		this.handleClick = this.handleClick.bind(this);
 }

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

猜你喜欢

转载自blog.csdn.net/qq_35504206/article/details/81704035