使用create-react-app脚本工具时初始化state可以用如下写法:
class Example extends React.Component{
state = {
name: "name"
}
onValueChange = (e) => {
this.setState({
name: e.target.value
})
}
render(){
return(
<div>
<input value={this.state.value} onChange={this.onValueChange}/>
</div>
)
}
}
该写法可以忽略constructor构造函数和绑定相应的方法,但是要用到在 类定义里申明属性,目前还是个 Proposal:
https://github.com/jeffmo/es-class-fields-and-static-properties
它不是 ES2015 的一部分,所以你的 Babel 得装这个插件:
npm install babel-plugin-transform-class-properties
然后在 .babelrc 里加上
{
“plugins”: [“transform-class-properties”]
}
具体可以看:
http://babeljs.io/docs/plugins/transform-class-properties
除了上述的 transform-class-properties ,babel还要能解析你的语句,所以还要下载一个插件:
npm install babel-plugin-syntax-class-properties
在.babelrc中添加:
{
“plugins”: [
“syntax-class-properties”,
“transform-class-properties”,
]
}