React Native 中的状态是什么?
状态是数据的来源。我们应该始终尝试使我们的状态尽可能简单,并尽量减少有状态组件的数量。例如,如果我们有 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 中的状态是什么?的详细内容,更多请关注双恒网络其它相关文章!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。



