react native 學習筆記之state

state狀態還是可以理解爲Android,ios中一個類的成員變量,而props和state的區別是,props一經指定,就不能修改,而state是可以修改的。一般來講,你需要在constructor中初始化state,然後在需要修改時調用setState方法。

下面是一個閃爍文字的例子。

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({ showText: !this.state.showText });
    }, 1000);
  }

  render() {
    // 根據當前showText的值決定是否顯示text內容
    let display = this.state.showText ? this.props.text : ' ';   //這就是大家熟悉的問號表達式,當狀態showText爲真時,                                                                //設置爲text。否者爲空.而showText被上面setInterval所控制

    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);

更多內容參看:http://reactnative.cn/docs/0.31/state.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章