(
问渠那得清如许,为有源头活水来。
双手奉上RN官网)
一般来说,你应该在构造方法中初始化state,当你想要改变state时调用setState来改变.
例如:让文字不停的闪烁效果
import React, { Component } from 'react';
import { AppRegistry, Text, View } from 'react-native';
//闪烁组件
class Blink extends Component {
//构造方法
constructor(props) {
//调用父类构造方法
super(props);
//初始化state
this.state = {showText: true};
//设置定时器1秒重设state. Toggle the state every second
setInterval(() => {
this.setState({ showText: !this.state.showText });
}, 1000);
}
render() {
//根据当前设置的是否显示文本来切换文本显示.实际上并不是隐藏文本,而是设置文本为空
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);
网友评论