在 react 中,组件的状态是一个对象,其中包含一些可能在组件的生命周期内发生变化的信息。最好尝试使状态尽可能简单,并尽量减少有状态组件的数量。
下面来看看如何创建一个带有消息状态的用户组件:
class User extends React.Component {
constructor(props) {
super(props)
this.state = {
message: 'Welcome to React world'
}
}
render() {
return (
<div>
<h1>{this.state.message}</h1>
</div>
)
}
}
state
与 props
非常相似,但它是私有的,完全由组件控制。即,在所有者组件决定传递它之前,任何其他组件都无法访问它。