前言

之前在写React的时候,关于state的一种写法一直没有看懂。

正常这样写:

1
2
3
4
5
6
7
8
9
10
11
12
class component extends React.Component {
constructor() {
this.state = {
x: 1,
}
this.aa = this.aa.bind(this)
}
function aa() {
console.log(this.state.x)
}
}

困惑的情形:

1
2
3
4
5
6
7
8
9
class component extends React.Component {
state = {
x: 1,
}
aa = () => {
console.log(this.state.x);
}
}

经过我的一番搜索,终于找到了答案,这是ES的一种新提案,并没有普及,使用的时候需要使用插件,叫做babel-plugin-transform-class-properties,它将原来将类属性写在constructor的写法简化为写在类中就可以了。

相关参考: