加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

React Native 入门(六) - State(状态)

发布时间:2020-12-15 06:43:48 所属栏目:百科 来源:网络整理
导读:当前 RN 版本:0.49 操作环境:Windows 10 props 是在父组件中指定的,并且传递给当前组件之后,是不能改变的。对于需要改变的数据,我们需要使用 state 。 初始化 在构造方法中初始化,并且有固定的格式,比如: constructor (props) { super(props); this.

当前 RN 版本:0.49
操作环境:Windows 10

props 是在父组件中指定的,并且传递给当前组件之后,是不能改变的。对于需要改变的数据,我们需要使用 state 。

初始化

在构造方法中初始化,并且有固定的格式,比如:

constructor(props) { super(props); this.state = { x: 0,y: 0 } }

通过 this.state = {} 的格式初始化 state,这里我们初始化了两个数据 x 和 y,它们的值都是 0 。

取值与改变值

通过 this.state.xx 取到需要的数据,比如:

var z = 1 + this.state.x;  // z = 1

通过 this.setState({}) 改变想要改变的数据:

this.setState({
      x: this.state.x + 1,y: this.state.x + 1
    })
var a = this.state.x; // a = 1
var b = this.state.y; // b = 1

这里需要注意一点,可能有的新手会认为,通过 x: this.state.x + 1 之后 x 的值变成了 1,那么再执行 y: this.state.x + 1 之后 y 的值应该是 2 才对。其实不是这样的,this.setState({}) 里面取到的 this.state.x 其实都是上一个状态的值,所以在它的里面 this.state.x 的值仍然是 0,于是 b 的值也就是 1 了。

一个例子

下面我们看一个例子:从 1 开始,点击按钮每次加 1,显示数字以及它的奇偶状态。

import React,{Component} from 'react';
import {
  View,Text,Button,StyleSheet
} from 'react-native';

export default class App extends Component<{}> {

  constructor(props) {
    super(props);
    this.state = {
      count: 1,type: '奇数'
    }
  }

  render() {
    return <View>
      <Text style={styles.text}>{this.state.count}</Text>
      <Text style={styles.text}>{this.state.type}</Text>
      <Button
          title={'喜加一'}
          onPress={() => {
            this.setState({
              count: this.state.count + 1,type: (this.state.count + 1) % 2 === 0 ? '偶数' : '奇数'
            })
          }}/>
    </View>
  }
}

const styles = StyleSheet.create({
  text: {
    textAlign: 'center',fontSize: 20
  }
})

与 Java 类似,我们也需要通过 import 方式导入用到的组件。

这里我们有两个 <Text/> 组件分别用来显示 count(数字) 与 type(奇偶数),一个 <Button/> 组件,点击它的时候改变 count 与 type 的值,相对应的 <Text/> 显示的文本也会发生改变。效果如下:

只要你在一个地方改变了 state 中的某个值,所有用到它的地方都会立即发生改变,是不是很方便呢?了解了这一点,我甚至有一点嫌弃原生的 Android 了。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读