在React中调用处理函数的最佳方法是什么?

问题描述 投票:1回答:1

我在阅读 ReactJs文档 关于 处理事件 我想知道在组件中调用处理函数的最佳实践是什么。

我的问题很简单(我认为甚至是基本的):在组件中的 onClick={handleClick}onClick={this.handleClick] ?

我看到这两段代码后,不知道其中的 handleClick 在调用时不使用关键字 this 在第一段代码中使用,在第二段代码中使用。

ActionLink() {
  function handleClick(e) {
    e.preventDefault();
    console.log('The link was clicked.');
  }

  return (
    <a href="#" onClick={handleClick}>
      Click me
    </a>
  );
}
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(state => ({
      isToggleOn: !state.isToggleOn
    }));
  }

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

ReactDOM.render(
  <Toggle />,
  document.getElementById('root')
);
javascript reactjs
1个回答
1
投票

他们是2种不同的情况。

  • onClick={handleClick} 是用在功能组件中,在一个函数中 this 关键的工作是指函数被调用时的地方,你不要用它。this 在功能组件中使用。
  • onClick={this.handleClick] 在类组件中使用。在类中你需要使用 this 关键工作是访问类属性,在这种情况下是函数。
© www.soinside.com 2019 - 2024. All rights reserved.