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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容