react native學習筆記(四)

State(狀態)

咱們使用兩種數據來控制一個組件:props和state。props是在父組件中指定,並且一經指定,在被指定的組件的生命週期中則再也不改變。 對於須要改變的數據,咱們須要使用state。react

通常來講,你須要在constructor中初始化state(譯註:這是ES6的寫法,早期的不少ES5的例子使用的是getInitialState方法來初始化state,這一作法會逐漸被淘汰),而後在須要修改時調用setState方法。redux

假如咱們須要製做一段不停閃爍的文字。文字內容自己在組件建立時就已經指定好了,因此文字內容應該是一個prop。而文字的顯示或隱藏的狀態(快速的顯隱切換就產生了閃爍的效果)則是隨着時間變化的,所以這一狀態應該寫到state中。react-native

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 : ' ';
    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、setTimeout等)中來操做state。典型的場景是在接收到服務器返回的新數據,或者在用戶輸入數據以後。你也可使用一些「狀態容器」好比Redux來統一管理數據流(譯註:但咱們不建議新手過早去學習redux)。服務器

State的工做原理和React.js徹底一致,因此對於處理state的一些更深刻的細節,你能夠參閱React.Component API。函數

看到這裏,你可能以爲咱們的例子老是千篇一概的黑色文本,太特麼無聊了。那麼咱們一塊兒來學習一下樣式吧。學習

相關文章
相關標籤/搜索