State状态控制
我们使用两种数据来控制一个组件:props
和state
。props
是在父组件中指定,而且一经指定,在被指定的组件的生命周期中则不再改变。 对于需要改变的数据,我们需要使用state
。
一般来说,你需要在constructor中初始化state
(译注:这是ES6的写法,早期的很多ES5的例子使用的是getInitialState方法来初始化state,这一做法会逐渐被淘汰,ES6和ES5写法对比),然后在需要修改时调用setState
方法。
现在在HelloWorld
中添加一个按钮,点击切换图片和文字
'use strict';
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Image
} from 'react-native';
import {
Page,
Button,
ViewPort
} from '@ctrip/crn';
class Greeting extends Component {
render() {
return (
<
Text
>
Hello {this.props.name}!
<
/Text
>
);
}
}
export default class Page1 extends Page {
constructor(props){
super(props)
this.state = {
index:0,
pics:[{uri:"http://m.vstou.com/img/201510/dm1_5.jpg"},{uri:"http://m.vstou.com/img/201510/dm2_5.jpg"}],
names:['CRN','RN']
}
}
render() {
const { pics , names , index } = this.state;
let pic = pics[index];
let name = names[index]
return (
<
ViewPort
>
<
Image source={pic} style={styles.image}
>
<
/Image
>
<
Greeting name={name}
>
<
/Greeting
>
<
Button onPress={this._onPress.bind(this)} textStyle={{color:'black'}}
>
点击切换
<
/Button
>
<
/ViewPort
>
);
}
_onPress(){
const { index } = this.state
let next = index ? 0 : 1
this.setState({
index:next
})
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
image:{
width:200,
height:200
}
});
效果图:
典型的场景是在接收到服务器返回的新数据,或者在用户输入数据之后。你也可以使用一些“状态容器”比如Redux来统一管理数据流(译注:但我们不建议新手过早去学习redux)。
现在您已经学习了props、state,可能会感觉到迷惑,它们俩是怎么样的关系,又该怎么区分使用,接下来看props vs state