美文网首页
5,React Native之State(状态)

5,React Native之State(状态)

作者: SYOL | 来源:发表于2017-04-26 08:42 被阅读325次

    我们使用两种数据来控制一个组件:props和state。props是在父组件中指定,而且一经指定,在被指定的组件的生命周期中则不再改变。 对于需要改变的数据,我们需要使用state。

    一般来说,你需要在constructor中初始化state(译注:这是ES6的写法,早期的很多ES5的例子使用的是getInitialState方法来初始化state,这一做法会逐渐被淘汰),然后在需要修改时调用setState方法。

    假如我们需要制作一段不停闪烁的文字。文字内容本身在组件创建时就已经指定好了,所以文字内容应该是一个prop。而文字的显示或隐藏的状态(快速的显隐切换就产生了闪烁的效果)则是随着时间变化的,因此这一状态应该写到state中。

    import React, { Component } from 'react';
    import {
      AppRegistry,
      StyleSheet,
      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 });
        }, 2000);
      }
    
      render() {
        // 根据当前showText的值决定是否显示text内容
        let display = this.state.showText ? this.props.text : ' ';
        return (
            <Text>{display}</Text>
        );
      }
    }
    
    class hyuxin extends Component {
      render() {
        return (
            <View>
              <Blink text='我在闪烁' />
              <Blink text='我在闪烁,以2秒速度闪烁' />
            </View>
        );
      }
    }
    const styles = StyleSheet.create({
    
    });
    
    AppRegistry.registerComponent('hyuxin', () => hyuxin);
    

    效果:

    1.gif

    实际开发中,我们一般不会在定时器函数(setInterval、setTimeout等)中来操作state。典型的场景是在接收到服务器返回的新数据,或者在用户输入数据之后。你也可以使用一些“状态容器”比如Redux来统一管理数据流(译注:但我们不建议新手过早去学习redux)。

    本文参考于http://reactnative.cn/docs/0.42/getting-started.html

    相关文章

      网友评论

          本文标题:5,React Native之State(状态)

          本文链接:https://www.haomeiwen.com/subject/hzgvzttx.html