创建一个有状态的组件(外界无法接触到他的state值,除非他传给他的子组件)
class StatefulComponent extends React.Component {
constructor(props) {
super(props);
// initialize state here
this.state = {
name:'xxx'
}
}
render() {
return (
<div>
<h1>{this.state.name}</h1>
</div>
);
}
};
你可以在组件的整个生命周期内访问state对象,你可以更新它、在 UI 中渲染它,也可以将其作为 props 传递给子组件。state对象的使用可以很简单,亦可以很复杂,就看你怎么用了。
以另一种方式在用户界面中渲染状态
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'freeCodeCamp'
}
}
render() {
// change code below this line
const name = this.state.name
// change code above this line
return (
<div>
{ /* change code below this line */ }
<h1>{name}</h1>
{ /* change code above this line */ }
</div>
);
}
};