React native学习第二章:State

来源:互联网 发布:瑜伽软件哪个好用 编辑:程序博客网 时间:2024/06/05 11:56

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

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

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

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);

一开始,我以为showText类似某种属性呢,然我我就想尝试做一个计时器改变图片的效果


import React, { Component } from 'react';import { AppRegistry, Text, View,Image } from 'react-native';class Blink extends Component {  constructor(props) {    super(props);    this.state = { showText2: true };     // 每1000毫秒对showText状态做一次取反操作     setInterval(() => {      this.setState({ showText2: !this.state.showText2 });     }, 1000);  }  render() {    // 根据当前showText的值决定是否显示text内容    let display = this.state.showText2 ? this.props.text : ' ';     return (      <Text  >{display}</Text>    );  }}class hideImage extends Component{    constructor(props) {    super(props);     this.state={changeImage:200};    // 每1000毫秒对showText状态做一次取反操作    setInterval(() => {       this.setState({changeImage:this.state.changeImage-10});    }, 1000);  }  render() {    // 根据当前showText的值决定是否显示text内容    let width21=this.state.changeImage;     let pic = {      uri: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg'    };    let pic2={        uri:'https://facebook.github.io/react/img/logo_og.png'    };    let showImage=width21>150?pic:pic2;    return (          <View>       <Image source={showImage} style={{width: 193, height: 110}} />             </View>    );  }    } class BlinkApp extends Component {  render() {    return (      <View>        <Blink text='I love to blink' />        <ChangeSize 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('LotsOfGreetings', () => hideImage);

正如上面所示并没有对state后面的名称有影响,感觉就是某种的变量,但是同时改变二个以上的变量,我还没的思路,比方说在改变图片的同时,想要改变大小这个怎么做,加载http的图片,我修改了plist文件配置,任然不能解决问题,只能说带着问题出发吧

0 0
原创粉丝点击