javascript - 在 ReactJS 组件中定义事件处理程序的正确方法是什么?

标签 javascript reactjs ecmascript-6

使用 JSX 语法在 ReactJS 组件中定义事件处理程序有不同的方法。

<input onChange={this.handleChange.bind(this)}></input>  // inline binding

还有

<input onChange={() => this.handleChange()}></input>  // using arrow function

两者都允许handleChange函数访问组件的this范围。

我一直使用第一种语法,因为它的可读性更清晰。

使用其中一种相对于另一种是否有任何优势或用例?

最佳答案

From the React Docs

class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }

  render() {
    // This syntax ensures `this` is bound within handleClick
    return (
      <button onClick={(e) => this.handleClick(e)}>
        Click me
      </button>
    );
  }
}

The problem with this syntax is that a different callback is created each time the LoggingButton renders. In most cases, this is fine. However, if this callback is passed as a prop to lower components, those components might do an extra re-rendering. We generally recommend binding in the constructor or using the property initializer syntax, to avoid this sort of performance problem.

因此,您应该使用bind,并且可以通过两种方式实现这一点。

From the React Docs

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

如果bind让你烦恼,那么你可以这样做

class LoggingButton extends React.Component {
  // This syntax ensures `this` is bound within handleClick.
  // Warning: this is *experimental* syntax.
  handleClick = () => {
    console.log('this is:', this);
  }

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

我能想到使用其中一种方法相对于另一种方法的唯一优点是,在顶级方法中,您可以将参数传递给 handleClick 函数。但我想不出在什么情况下你可以这样做。

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};
  }

  handleClick(e, something) {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
    alert(something)
  }

  render() {
    return (
      <button onClick={(e) => this.handleClick(e, "Yo!")}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }
}

ReactDOM.render(
  <Toggle />,
  document.getElementById('root')
);

关于javascript - 在 ReactJS 组件中定义事件处理程序的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45690110/

相关文章:

javascript - 错误地返回一个对象?

javascript - 功能没有出现在浏览器中

javascript - react native : is it possible to stop PanResponder event inside onPanResponderMove?

javascript - 如何重置或取消选中同名单选按钮的值

javascript - React js中点击element1时如何执行对element2的点击?

reactjs - 使用react-leaflet渲染GeoJSON

javascript - JS中只接收一个参数

javascript - 将事件绑定(bind)到 Web 组件中的模板文字的最便捷方法是什么?

javascript - 在 IE 11 中加载 block 失败

javascript - IE8 iframe 无法成功运行 JS/CSS 代码