React-Native 动态属性state

来源:互联网 发布:linux安装输入法 编辑:程序博客网 时间:2024/05/27 08:13

如果是需要涉及到动态变化,就需要使用state这个属性了
示例如下:

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(previousState => {        return { showText: !previousState.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);

其中setInterval()属于定时器函数,用于定时执行相关逻辑。
this.props.text 指的是Blink里面text属性的值。
this.setState()用于设置state的属性值。

this.setState(previousState => {        return { showText: !previousState.showText };      });

以上这句的意思是使用setState(previousState);而previousState这个值是由以下决定的

{        return { showText: !previousState.showText };      }
原创粉丝点击