美文网首页
004_ReactNative: State

004_ReactNative: State

作者: 莫_名 | 来源:发表于2016-08-21 13:03 被阅读0次

    (问渠那得清如许,为有源头活水来。 双手奉上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);
    
    

    相关文章

      网友评论

          本文标题:004_ReactNative: State

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