状态是数据的来源。我们应该始终尝试使我们的状态尽可能简单,并尽量减少有状态组件的数量。例如,如果我们有 10 个需要状态数据的组件,我们应该创建一个容器组件来保存所有这些组件的状态。
示例 1
当用户按下按钮时,按钮标题更改为ON/OFF。
状态在构造函数内初始化,如下所示 –
constructor(props) {
super(props);
this.state = { isToggle: true };
}
登录后复制
isToggle 是赋予状态的布尔值。按钮的标题是根据 isToggle 属性决定的。如果值为 true,则按钮的标题为 ON,否则为 OFF。
当按下按钮时,将调用 onpress 方法,该方法会调用更新 isToggle 值的 setState,如下所示 –
onPress={() => {
this.setState({ isToggle: !this.state.isToggle });
}}
登录后复制
当用户单击按钮时,将调用 onPress 事件,并且 setState 将更改 isToggle 属性的状态。
App.js
import React, { Component } from "react";
import { Text, View, Button, Alert } from 'react-native';
class App extends Component {
constructor(props) {
super(props);
this.state = { isToggle: true };
}
render(props) {
return (
<View style={{flex :1, justifyContent: 'center', margin: 15 }}>
<Button
onPress={() => {
this.setState({ isToggle: !this.state.isToggle });
}}
title={
this.state.isToggle ? 'ON' : "OFF"
}
color="green"
/>
</View>
);
}
}
export default App;
登录后复制
输出
当用户按下按钮时,按钮将切换。
示例 2
在用户单击文本时更改文本。
在下面的示例中,状态在构造函数内显示如下 –
constructor(props) {
super(props);
this.state = { myState: 'Welcome to Tutorialspoint' };
}
登录后复制
状态 myState 显示在 Text 组件内,如下 –
<Text onPress={this.changeState} style={{color:'red', fontSize:25}}>{this.state.myState} </Text>
登录后复制
当用户触摸或按下文本时,会触发 onPress 事件并调用 this.changeState 方法,该方法通过更新状态 myState 来更改文本,如下所示 –
changeState = () => this.setState({myState: 'Hello World'})
登录后复制
import React, { Component } from "react";
import { Text, View, Button, Alert } from 'react-native';
class App extends Component {
constructor(props) {
super(props);
this.state = { myState: 'Welcome to Tutorialspoint' };
}
changeState = () => this.setState({myState: 'Hello World'})
render(props) {
return (
<View style={{flex :1, justifyContent: 'center', margin: 15 }}>
<View>
<Text onPress={this.changeState} style={{color:'red', fontSize:25}}> {this.state.myState} </Text>
</View>
</View>
);
}
}
export default App;
登录后复制
输出
以上就是React Native 中的状态是什么?的详细内容,更多请关注www.92cms.cn其它相关文章!






