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。函数

看到这里,你可能以为咱们的例子老是千篇一概的黑色文本,太特么无聊了。那么咱们一块儿来学习一下样式吧。学习

相关文章
相关标签/搜索