Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/436.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript React.js和arrow函数与普通函数_Javascript_Reactjs_Arrow Functions - Fatal编程技术网

Javascript React.js和arrow函数与普通函数

Javascript React.js和arrow函数与普通函数,javascript,reactjs,arrow-functions,Javascript,Reactjs,Arrow Functions,我当时正在开发一个react.js应用程序,最初我使用了arrow函数,但出于好奇,我决定尝试正常函数,但正常函数不起作用。我认为他们都应该输出相同的东西,出了什么问题 handleChange = event => this.setState({init: event.target.value}) handleChange(event){ this.setState({init: event.target.value}) } 箭头功能和正常功能不等效 区别如下: 箭头函数没有自己

我当时正在开发一个react.js应用程序,最初我使用了arrow函数,但出于好奇,我决定尝试正常函数,但正常函数不起作用。我认为他们都应该输出相同的东西,出了什么问题

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

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

箭头功能和正常功能不等效

区别如下:

  • 箭头函数没有自己的
    this
    绑定,因此您的
    this.setState
    请参考
    YourClass.setState

  • 使用普通函数,您需要将其绑定到类以获得类的
    引用。因此,当您调用
    this.setState
    时,实际上它指的是
    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
        }
    }
    

    检查您正在使用的es版本。根据这一点,您应该使用语法。如果缺少必要的模块,它将给出错误提示