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

前端 未结 1 670
情歌与酒
情歌与酒 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 (
          
        );
      }
    }
    
    // Render it
    ReactDOM.render(
      ,
      document.getElementById("react")
    );

    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 (
          
        );
      }
    }
    
    // Render it
    ReactDOM.render(
      ,
      document.getElementById("react")
    );

    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)
提交回复
热议问题