React Native 入门(六)

来源:互联网 发布:tplink访客网络设置 编辑:程序博客网 时间:2024/05/21 10:29

当前 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 = 1var 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 了。

文章已同步至简书:http://www.jianshu.com/p/265e62601ff8

原创粉丝点击