一、介绍
一个组件有两种属性控制:props(控制静态数据)
和state(控制动态数据)
。
props用
于需要静态数据(它在父组件中指定,而且一经指定,在被指定的组件的生命周期中则不再改变)。
state用
于需要改变的数据。
一般来在constructor中初始化state
,然后在需要修改时调用setState
方法。
二、举例
假如我们需要制作一段不停闪烁的文字。
分析:
1.文字内容本身在组件创建时就已经指定好了,所以文字内容应该是一个prop
。
2.而文字的显示或隐藏的状态则是随着时间变化的,因此这一状态应该写到state
中。
代码:
1.自定义组件 Blink ,文字显示内容用props指定
<Blink text='I love to blink' />
2.自定义组件 Blink ,constructor中初始化state
显示文字,在setInterval中每1000毫秒让state取反
class Blink extends Component{
constructor(props){
super(props);
this.state = {showtext:true};
// 每1000毫秒对showText状态做一次取反操作
setInterval( ()=> { this.setState({showtext:!this.state.showtext}); },500 );
}
render(){
// 根据当前showText的值决定是否显示text内容
let display = this.state.showtext?this.props.text:'';
return(
<Text>{display}</Text>
)
}
}
3.主入口
export default class myprojectname extends Component<Props> {
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>
);
}
}
// 注意,这里用引号括起来的'myprojectname'必须和你init创建的项目名一致
AppRegistry.registerComponent('myprojectname', () => myprojectname);
4.效果