What is the difference between passing a function name in onclick react and calling it through callback

前端 未结 1 663
情歌与酒
情歌与酒 2021-01-26 20:44

I want to know the difference between these two statements in react.



相关标签:
1条回答
  • 2021-01-26 21:42

    If the function depends on having a calling context of the instance, and the function isn't bound to the current instance already, the first code won't work, because the this inside callMe will be undefined:

    class Component extends React.Component {
      name = 'component_name';
      Callme() {
        console.log(this.name);
      }
      render() {
        return (
          <button onClick={this.Callme}>Click</button>
        );
      }
    }
    
    // Render it
    ReactDOM.render(
      <Component />,
      document.getElementById("react")
    );
    <div id="react"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

    The second code works, because the this in the anonymous arrow function will inherit the this from the outer scope, the instance:

    class Component extends React.Component {
      name = 'component_name';
      Callme() {
        console.log(this.name);
      }
      render() {
        return (
          <button onClick={() => this.Callme()}>Click</button>
        );
      }
    }
    
    // Render it
    ReactDOM.render(
      <Component />,
      document.getElementById("react")
    );
    <div id="react"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

    If the Callme method does not need to refer to the instance, then either type of onClick works.

    Other solutions to this common problem include:

    • Binding the method in the constructor (this.Callme = this.Callme.bind(this))
    • Binding the method when setting the callback (onClick={this.Callme.bind(this)}>)
    • Defining the method as an arrow function in the constructor (or as a class field), rather than as a property of the prototype

      class Component extends React.Component {
        this.Callme = () => {
          console.log(this.name);
        }
      
    0 讨论(0)
提交回复
热议问题