美文网首页程序员@IT·互联网编程
React native之路(九)理解State

React native之路(九)理解State

作者: Knight_Davion | 来源:发表于2017-04-17 11:16 被阅读387次

React native的组件可以通过两种方式进行状态控制,一种是Props用来设置不会改变的数据,另一种就是State,用来设置会变换的数据。State相当重要,所有的UI界面变化都离不开State。
State的使用方式是:

  1. 在组件的构造函数中初始化State;
  2. 在合适的地方调用setState方法;

首先来看官方的例子,官方给出了一个文字闪烁的效果,具体代码

class Blink extends Component {
  constructor(props) {
      super(props);
      this.state = {showText: true};//这里设置了一个boolean型的showText,默认值为true;

      // Toggle the state every second
      setInterval(() => {
        this.setState({ showText: !this.state.showText });
      }, 1000);//这里是一个定时器,每1s会执行一次,调用定时器中的方法,重新给state赋值,注意this.state.showText是获取当前showText的值,同时需要注意的是调用this.setState()后回自动调用 render() 方法从而实现界面的刷新。
    }
    render() {
      let display = this.state.showText ? this.props.text : ' ';//这里通过showText 的值决定diaplay的值,如果为ture 则显示this.props.text属性的值,否则显示‘ ’,this.props.text为自定义属性,let等同于var;
      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);

显示结果如下:


再来看一个其他的例子:
我们要实现这样一个效果



点击按钮改变按钮的背景色,来看代码

class MyButton extends Component{
  constructor(props) {
    super(props);
    this.state = {clickable:false};
  }

  toggleColor=()=> {
    this.setState({
      clickable:!this.state.clickable
    })
  }

  render(){
    return(
        <TouchableOpacity onPress={this.toggleColor}>
          <View style={{justifyContent:'center',alignItems:'center',width:100,height:56,backgroundColor:this.state.clickable?'#ff00ff':'#00ffff'}}>
          <Text >点我</Text>
          </View>
        </TouchableOpacity>
      );
  }
}

具体流程如下:
1 定义了一个MyButton 组件;
2在MyButton 的构造函数中声明了一个clickable;
3定义一个toggleColor方法并在其中通过this.setState完成clickable值的改变;
4在render函数中通过TouchableOpacity 自定义了一个button,并通过onPress调用toggleColor方法。

调用MyButton

class HelloWorld extends Component{
  render(){
    return(
        <View style={{justifyContent:'center',alignItems:'center',flex:1}}>
            <MyButton/>
        </View>
      );
  }
}

显示效果如上图所示。
State的使用也就是这些了,关键是记住其使用方式即可。

相关文章

网友评论

    本文标题:React native之路(九)理解State

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