CNode

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

问答
BBubblyFace发布于9 年前最后回复9 年前6 回复5099 浏览0 收藏

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

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

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

查看回复

回复 (6)

M
MiYogurt#1·9 年前

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

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

B
BubblyFace#2·9 年前
引用 MiYogurtes6 不支持属性写法,除非是 ts,或者用可以写属性的 babel 插件。 在 ctor 里面绑定 this 的写法也不是这样的.

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

A
atian25#3·9 年前

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

class test{
	handleChange()  {
		  // call this function from render 
		  // and this.whatever in here works fine.
	};
}
Y
yinxin630#4·9 年前

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

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

@atian25 了解了 感谢回答

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