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 (
      {display}
    );
  }
}

class BlinkApp extends Component {
  render() {
    return (
      
        
        
        
        
      
    );
  }
}

AppRegistry.registerComponent('BlinkApp', () => BlinkApp);

你可能感兴趣的:(004_ReactNative: State)