004_ReactNative: State

(问渠那得清如许,为有源头活水来。 双手奉上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);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容