将状态从子级传递到React Native中的父级组件 [英] Pass state from child to parent component in React Native

查看:110
本文介绍了将状态从子级传递到React Native中的父级组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序有一个设置屏幕(子组件),您可以在其中更改有关您自己的信息,而我试图将其呈现在应用程序的配置文件屏幕(父组件)上.因此,配置文件屏幕显示您的信息,如果您想更改任何信息,请在设置中进行.现在,我在设置屏幕中所做的任何更改都会显示在Firebase中,但是如果我返回到配置文件屏幕,则设置中的更改不会呈现.当然,如果我关闭该应用程序并重新加载它,更改将在那里,因为设置的更改正在注册到Firebase中.但是,状态并未从子组件传递到父组件.有人对如何将状态从设置(子级)组件传递到配置文件(父级)组件有任何建议吗?

My app has a settings screen (child component) where you can change information about yourself and I'm trying to get that to render on my app's profile screen (parent component). So the profile screen displays your info and if you want to change any info you do it in settings. Right now any changes I make in the settings screen show up in Firebase but if I go back to the profile screen the changes in settings don't render. Of course if I close the app and reload it the changes will be there because the changes in settings are registering to firebase; however, the state is not passing up from the child component to the parent. Does anyone have any advice on how to pass state from the settings (child) component up to the profile (parent) component?

推荐答案

您可以尝试使用redux,每当您在redux存储中更改数据时,它都会以props的状态存储数据.

You can try redux, It store data in state by props whenever you change data in redux store.

另一个想法是,将setState方法传递给子组件.

Other idea is, pass a setState method to child component.

class Parent extends Component {
    updateState (data) {
        this.setState(data);
    }
    render() {
        <View>
            <Child updateParentState={this.updateState.bind(this)} />
        </View>
    }
}

孩子

class Child extends Component {
    updateParentState(data) {
        this.props.updateParentState(data);
    }

    render() {
        <View>
            <Button title="Change" onPress={() => {this.updateParentState({name: 'test'})}} />
        </View>
    }
}

这篇关于将状态从子级传递到React Native中的父级组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆