React.js and arrow functions vs normal functions [duplicate]

故事扮演 提交于 2019-12-11 18:13:28

问题


I was working on a react.js app and I initially used the arrow function which worked, but then just out of curiosity I decided to try the normal function and the normal function didn't work. I think that they both should output the same thing, what is going wrong?

handleChange = event => this.setState({init: event.target.value})

handleChange(event){
  this.setState({init: event.target.value})
}

回答1:


Arrow functions and normal function are not equivalent.

Here is the difference:

  1. Arrow function do not have their own binding of this, so your this.setState refer to the YourClass.setState.

  2. Using normal function, you need to bind it to the class to obtain Class's this reference. So when you call this.setState actually it refer to YourFunction.setState().

Sample Code

class FancyComponent extends Component {
    handleChange(event) {
        this.setState({ event }) // `this` is instance of handleChange
    }

    handleChange = (event) => {
        this.setState({ event }) // `this` is instance of FancyComponent
    }
}


来源:https://stackoverflow.com/questions/51778443/react-js-and-arrow-functions-vs-normal-functions

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