我们使用两种数据来控制一个组件: Props和State。Props是在父组件中指定,而且一经指定,在被指定或者使用的组件的生命周期中则不再改变。对于组件内需要改变的数据,则需要使用 State。
一般来说,需要在constructor中初始化state,然后在需要修改时调用setState方法。
初始化代码:
constructor(props){
super(props);
this.state={
showText:'Welcome to React Native!',
};
};
得到某一个具体的State值时,使用以下两种方式:
1-:
let showText=this.state.showText;
2-:
const {showText} =this.state;
修改时代码:
this.setState({
showText:'使用setState进行状态修改',
});
运行以下例子:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
export default class LearnDay extends Component {
constructor(props){
super(props);
this.state={
showText:'Welcome to React Native!',
};
};
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
{this.state.showText}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
color:'red'
},
});
AppRegistry.registerComponent('LearnDay', () => LearnDay);
注意:
1-:{this.state.showText}外面有一层括号我们需要用括号。需要用括号这个变量嵌入到JSX语句中。括号的意思是括号内部为一个js变量或表达式,需要执行后取值。因此我们可以把任意合法的JavaScript表达式通过括号嵌入到JSX语句中。
2-:使用State定义的值时,使用以下样式进行取值:
this.state.XXXX
扩展知识:setState是一个异步函数,所谓“异步”,是不能“那么快”取到修改后的值,需使用以下函数来进行取值。
应使用如下方式:
this.setState({
showText:'修改后的showText'
},()=>{
//setState后的操作,可以立即取到更新后的值:
alert(this.state.showText);
})