跳到主要内容
CNode

为什么在自己搭建react项目或者在chrome里,在class中使用箭头函数来定义方法会报错

问答
BBubblyFace发布于 9 年前最后回复 9 年前
651190

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

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

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

查看回复

回复 (6)

B
BubblyFace#59 年前
引用 atian25因为这语法不是合法的 class 语法.

@atian25 了解了 感谢回答

Y
yinxin630#49 年前

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

A
atian25#39 年前

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

class test{
	handleChange()  {
		  // call this function from render 
		  // and this.whatever in here works fine.
	};
}
B
BubblyFace#29 年前
引用 MiYogurtes6 不支持属性写法,除非是 ts,或者用可以写属性的 babel 插件。 在 ctor 里面绑定 this 的写法也不是这样的.

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

M
MiYogurt#19 年前

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

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

参与回复

登录后即可参与回复。登录