React - Arrow functions and this and scope

别等时光非礼了梦想. 提交于 2019-12-11 04:27:15

问题


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>


来源:https://stackoverflow.com/questions/47400259/react-arrow-functions-and-this-and-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!