react-native - 如何在 react-native 中更改父级的变量
问题描述
我想改变client = {state:0}
你可以通过使用访问它this.client.state
我也有一个包含按钮的孩子。当您按下按钮时,我正在尝试更改此“状态”变量。
出于某种原因,我发现互联网上的所有内容都不适合我。我已经坚持了 5 个小时,我想是时候自己寻求帮助了
import React from 'react';
import { StyleSheet, Text, View, Image, TouchableOpacity } from 'react-native';
import Home from './Components/Home';
import Activity from './Components/Activity';
export default class App extends React.Component {
client = {state:0}
render() {
if(this.client.state == 0){
return(
<View style={{flex: 1}}>
<Home />
<Child />
</View>
);
} else {
return(
<View style={{flex: 1}}>
<Activity />
<Child />
</View>
);
}
解决方案
有不同的方法可以做到这一点。例如,可以使用 Redux 来完成,但让我们采用更简单的方法。
另请注意,它不能由 props 完成,因为子组件无法更新其父组件的 props。
另请注意,您使用状态的方式似乎很奇怪。它应该设置在类级别(或组件级别)。
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {myProperty: 0};
}
}
您可以将回调方法传递给子 React 组件。
<Child callback={this.onButtonClick} />
在Client
组件上,创建回调方法:
onButtonClick() {
this.setState({buttonClicked: true});
}
为了保持干净,在构造函数中定义初始值。您还必须绑定函数以获得正确的 this 参数,否则this
变量将来自事件而不是您期望的类。
constructor(props) {
super(props);
this.state = {buttonClicked: false};
this.onButtonClick = this.onButtonClick.bind(this);
}
这就是Client
组件。
现在在Child
组件上,您需要尽可能触发此回调方法。
想象一下 Child 有以下按钮,在子组件上也添加一个事件处理程序,onChildButtonClick
. 您还必须在构造函数中进行绑定。
constructor(props) {
super(props);
// bind this for access to this class' data
this.onChildButtonClick = this.onChildButtonClick.bind(this);
}
onChildButtonClick() {
// Might want to do a typeof is function check here too
if (this.props.callback) {
// Trigger the callback on the parent component, letting it know the button was triggered
this.props.callback();
}
}
render() {
return <button onClick={this.onChildButtonClick}>Click me</button>;
}
在初始化期间,父组件向子组件发送回调方法。每当点击子组件上的按钮时,子组件都会触发父组件给定的函数(回调),本质上是在父组件上运行一段代码,然后用请求的值更新状态(可以是字符串,或任何东西)。
还原
Redux 是另一种实现方式,它基本上保持了一种database
可以通过页面加载从任何组件中使用的跟踪 - 但是,这需要完整的教程。
推荐阅读
- php - 在 wordpress 后端为自定义帖子、分类和元创建导出到 CSV 按钮
- r - 通过未导出的函数方法定位包
- kotlin - Kotin 应用程序在使用 fixedRateTimer 时不会停止(即使窗口关闭)
- ios - React Native - PhaseScriptExecution 错误
- maven - 如何在 Maven POM 文件的一部分中对依赖项进行排序
- angular8 - 未捕获的错误:无法绑定到“FormGroup”,因为它不是“form”的已知属性
- javascript - Node.js 中的“非池化”缓冲区是什么?
- visual-studio-2017 - Visual Studio Azure 功能解决方案中存在 XML 文件未发布到 Azure
- azure-logic-apps - 读取 XML 文件并通过 Azure 逻辑应用获取具有相应值的标签
- r - 如何从R中的时间元素获取日期?