React 中的哪种绑定上下文方法(ES6 类)更好

Which method of binding context in React (ES6 classes) is better

本文关键字:ES6 更好 方法 上下文 绑定 React      更新时间:2023-09-26

在 React ES6 类中没有自动绑定。因此,开发人员有两种选择来绑定上下文:

1) 在构造函数中

export class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myFunction = this.myFunction.bind(this);
  }
  myFunction() {
    // do something
  }
  render() {
    return (
      <div onClick={this.myFunction}></div>
    );
  }
}

2) 内联法

export class MyComponent extends React.Component {
  constructor(props) {
    super(props);
  }
  myFunction() {
    // do something
  }
  render() {
    return (
      <div onClick={this.myFunction.bind(this)}></div>
    );
  }
}

哪种方法更有效率?

我推荐箭头函数。

export class MyComponent extends React.Component {
  constructor(props) {
    super(props);
  }
  myFunction = (e) => {
    // e.preventDefault()
    // do something
  }
  render() {
    return (
      <div onClick={e => this.myFunction(e)}></div>
    );
  }
}

不再需要bind()

对于处理程序函数,当它们作为普通函数调用时,这是指全局对象。当使用 ECMAScript 6 类而不是 React.createClass() 时,就会发生这种情况,后者在引擎盖下具有自动绑定功能。两种方法可以按预期实现绑定的效果。第一种方法,使用如下语法显式绑定处理程序函数。

constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
}
handleChange() {}

另一种方法是以这种方式编写组件的处理程序属性,而不绑定任何内容。

<MyComponent onChange={() => this.handleChange()}><MyComponent />

这样,处理程序只会在触发相应的事件时被调用,此时,this引用组件实例,这是我们期望它引用的。

这两种方法都可以工作,决定使用哪种方法是您的决定。