简体   繁体   中英

What is the best way to call a handling function in React?

I was reading the ReactJs documentation about Handling events and I wondered what the best practice is for calling a handling function in a component.

My question is very simple (and even basic I think): what should be used between onClick={handleClick} or onClick={this.handleClick] ?

I wonder after seeing these two pieces of code in which handleClick is called without the keyword this in the first code and with in the second code.

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

They are 2 different situations.

  • onClick={handleClick} is used in functional component, in a function this key work is refer to the place when the function is call, you don't use this in functional component.
  • onClick={this.handleClick] is used in class component. In class you need to use this key work to access class property which is function in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM