状态是数据的来源。我们应该始终尝试使我们的状态尽可能简单,并尽量减少有状态组件的数量。例如,如果我们有 10 个需要状态数据的组件,我们应该创建一个容器组件来保存所有这些组件的状态。
当用户按下按钮时,按钮标题更改为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;当用户按下按钮时,按钮将切换。

网站模板是能够具有交互性,能够包含更多活跃的元素,就有必要在网页中嵌入其它的技术。如:Javascript、VBScript、Document Object Model(DOM,文档对象模型)、Layers和 Cascading Style Sheets(CSS,层叠样式表),这里主要讲Javascript。那么Javascript是什么东西?Javascript就是适应动态网页制作的需要而诞生的
70
在用户单击文本时更改文本。
在下面的示例中,状态在构造函数内显示如下 -
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 中的状态是什么?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号