1. 程式人生 > >有關React的State初始化的問題

有關React的State初始化的問題

使用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”,
]
}