react类组件中方法绑定到类实例

80 阅读1分钟

在JS中this会根据当前执行上下文变化,在React类组件方法中希望this引用的是当前的实例,因此有必要将这些方法绑定到当前实例。

  • constructor构造函数中绑定this。
export default class Home extends React.Component {
  constructor() {
    super();
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    // ...
  }

  render() {
    return (
      <button onClick={this.handleClick}>123</button>
    )
  }
}
  • 定义函数时使用箭头函数。
export default class Home extends React.Component {
  handleClick = () => {
    // ...
  }

  render() {
    return (
      <button onClick={this.handleClick}>123</button>
    )
  }
}
  • 调用函数时绑定this。
export default class Home extends React.Component {
  handleClick() {
    // ...
  }

  render() {
    return (
      <button onClick={this.handleClick.bind(this)}>123</button>
    )
  }
}
  • 调用函数时使用箭头函数。
export default class Home extends React.Component {
  handleClick() {
    // ...
  }

  render() {
    return (
      <button onClick={() => this.handleClick()}>123</button>
    )
  }
}