React.js和Arrow函数与普通函数 [英] React.js and arrow functions vs normal functions

查看:69
本文介绍了React.js和Arrow函数与普通函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当时正在使用react.js应用程序,最初使用的是箭头功能,但出于好奇,我决定尝试使用正常功能,但正常功能无效.我认为他们俩都应该输出相同的内容,这是怎么回事?

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})
}

推荐答案

箭头功能和普通功能不相同.

Arrow functions and normal function are not equivalent.

这是区别:

  1. 箭头功能没有具有其自己的this绑定,因此您的this.setState引用了YourClass.setState.

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

使用常规功能,您需要将其绑定到类以获得Class的this引用.因此,当您呼叫this.setState时,它实际上是指YourFunction.setState().

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().

示例代码

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

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

这篇关于React.js和Arrow函数与普通函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆