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

前端之家收集整理的这篇文章主要介绍了React Native 入门(六) - State(状态)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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

初始化

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

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

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

取值与改变值

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

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

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

  1. this.setState({
  2. x: this.state.x + 1,y: this.state.x + 1
  3. })
  4. var a = this.state.x; // a = 1
  5. 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,显示数字以及它的奇偶状态。

  1. import React,{Component} from 'react';
  2. import {
  3. View,Text,Button,StyleSheet
  4. } from 'react-native';
  5.  
  6. export default class App extends Component<{}> {
  7.  
  8. constructor(props) {
  9. super(props);
  10. this.state = {
  11. count: 1,type: '奇数'
  12. }
  13. }
  14.  
  15. render() {
  16. return <View>
  17. <Text style={styles.text}>{this.state.count}</Text>
  18. <Text style={styles.text}>{this.state.type}</Text>
  19. <Button
  20. title={'喜加一'}
  21. onPress={() => {
  22. this.setState({
  23. count: this.state.count + 1,type: (this.state.count + 1) % 2 === 0 ? '偶数' : '奇数'
  24. })
  25. }}/>
  26. </View>
  27. }
  28. }
  29.  
  30. const styles = StyleSheet.create({
  31. text: {
  32. textAlign: 'center',fontSize: 20
  33. }
  34. })

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

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

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

猜你在找的React相关文章