React - Arrow functions and this and scope

2019-08-12 05:24发布

问题:

I have the following code.

let myapp = this;
      myref.on('value', function (snapshot) {
        myapp.updateUsers();
    });

I am trying to get rid of the code which fixes the scope issue. Can I convert this to an ES6 arrow function?

Alternatively is there a way to access the react root app?

 class App extends Component {}

回答1:

When you are inside a class and using an arrow function then this will get its reference binding to the instance via the lexical scope, instead of dynamic binding like you get with plain normal functions.
So when you want to use a method within the class you can reference the class instance with the this key word:

someFunction = () => {this.updateUsers()}

Simple Example:

class App extends React.Component {
  
  myfunc1 = (str) => {
    console.log(str);
  }

  myFunc2 = () => {
    this.myfunc1('hi func 2')
  }

  render() {
    return (
      <div>
        <button onClick={this.myFunc2}>Click Me</button>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<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>
<div id="root"></div>