首页 > 解决方案 > 如何在 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>
        );
    }

标签: react-native

解决方案


有不同的方法可以做到这一点。例如,可以使用 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可以通过页面加载从任何组件中使用的跟踪 - 但是,这需要完整的教程。


推荐阅读