React-Native:State
之前说的props
是在父组件中指定的,而且一经指定,在被指定的组件的生命周期中不再改变。对于需要改变的数据,我们应该使用state
(状态)。
一般在constructor
中来初始化state
,然后在需要修改时调用setState
方法。
例子:做一段不断闪烁的文字:
class Blank extends Component {
constructor(props){
super(props);
this.state = { showText: true }; // 初始化state
// 每过1ms调用setState改变状态
setInterval(() => {
this.setState(previousState => {
return { showText: !previousState.showText };
});
},1);
}
render(){
let display = this.state.showText ? this.props.text : '';
return (
<Text>{display}</Text>
);
}
}
网友评论