State(状态)

时间:2023-03-09 02:58:01
State(状态)

propsstateprops是在父组件中指定,而且一经指定,在被指定的组件的生命周期中则不再改变。 对于需要改变的数据,我们需要使用state。般来说,你需要在constructor中初始化state(译注:这是ES6的写法,早期的很多ES5的例子使用的是getInitialState方法来初始化state,这一做法会逐渐被淘汰),然后在需要修改时调用setState方法。

import React, { Component } from 'react';
import { AppRegistry, Text, View } from 'react-native'; class Blink extends Component {
constructor(props) {
super(props);
this.state = { showText: true }; // 每1000毫秒对showText状态做一次取反操作
setInterval(() => {
this.setState({ showText: !this.state.showText });
}, 1000);
} render() {
// 根据当前showText的值决定是否显示text内容
let display = this.state.showText ? this.props.text : ' ';
return (
<Text>{display}</Text>
);
}
} class BlinkApp extends Component {
render() {
return (
<View>
<Blink text='I love to blink' />
<Blink text='Yes blinking is so great' />
<Blink text='Why did they ever take this out of HTML' />
<Blink text='Look at me look at me look at me' />
</View>
);
}
}
AppRegistry.registerComponent('BlinkApp', () => BlinkApp);