在构造中定义变量并在模板中使用它们与在 getInitialState() 函数内部定义有什么区别?
在 ES6 中,我可以忘记使用 getInitialState() 并在构造上移动所有内容吗?
例子:
class TodoApp extends Component {
constructor() {
super();
this.test1 = 'hello this is a test';
this.state = { // thanks to @Piotr Berebecki,
// i know to define states variable
test2:'this is state test'
}
}
changeTest () {
this.state.test2 = 'my new state test';
}
render() {
return (
<div>
<button onClick={this.changeTest}>change</button>
Test:{this.test1}
<br/>State Test:{this.test2}
</div>
);
}
}
ReactDOM.render(
<TodoApp />,
document.getElementById('app')
);