React → Handling Events 绑定事件

2017-11-28  本文已影响7人  McDu
  1. With JSX you pass a function as the event handler, rather than a string.
  2. you cannot return false to prevent default behavior in React. You must call preventDefault explicitly.
  3. react 里事件里的 e 是包装过的, 所以你不必考虑浏览器兼容性. SyntheticEvent
  4. react 里 this 指向:
    ES6 里 class B 继承 A 时, this 指向 B.
class B extends A {
  constructor(){
    super();
    this.a = 1;
  }
}

1. 在 constructor 里 bind(this)

react 里给 element 绑定一个事件, 就要在 constructor 里指明事件的 this 指向.

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>
    );
  }
}

如果不在 constructor 里绑定 this, 也可以用 onClick={this.handleClick.bind(this)} 来绑定.

2. 使用箭头函数,返回一个匿名函数

如果不想调用 bind 方法, 可以使用 ES6 的箭头函数, 箭头函数里的 this 是定义时的环境.onClick={(e) =>this.handleClick(e)}.

注意:使用箭头函数必须显式传入一个参数 e, 事件处理函数才能得到 e, ES5 bind方法不用.

如果处理函数是这样的:

 handleClick(e) {
    console.log(e)
  }

那么 onClick={this.handleClick.bind(this)}onClick={(e) =>this.handleClick(e)} 的写法均能输出 e.

还有一种 实验性的 公共类字段的写法, 不用调用bind.

handleClick = () => {
    console.log('this is:', this);
}
 // onClick={this.handleClick} 这样写就好了

This syntax is enabled by default in Create React App.

3. 使用装饰器

类的修饰


Handling Events

上一篇 下一篇

猜你喜欢

热点阅读