为什么在自己搭建react项目或者在chrome里,在class中使用箭头函数来定义方法会报错
发布于 7 年前 作者 BubblyFace 4005 次浏览 来自 问答

在看react的this绑定的时候看到了一个解决方法:

class test{
	handleChange = () => {
		  // call this function from render 
		  // and this.whatever in here works fine.
	};
}

这种写法可以不用在constructor中绑定this 这种方式我在自己搭建的react和浏览器直接运行时都会报错这是为什么呢

6 回复

es6 不支持属性写法,除非是 ts,或者用可以写属性的 babel 插件。

在 ctor 里面绑定 this 的写法也不是这样的.

@MiYogur 谢谢回答,看来是这样吧。。。不过我上边并不是在ctor里绑定this。

因为这语法不是合法的 class 语法.

class test{
	handleChange()  {
		  // call this function from render 
		  // and this.whatever in here works fine.
	};
}

这个语法需要babel编译, 我的项目里面用的stage-2, 支持该语法

@atian25 了解了 感谢回答

@yinxin630 了解了 谢谢您了

回到顶部