Unable to call or update state of another componen

2019-08-31 18:53发布

问题:

I am unable to fire a method on the parent component when I click a button from a child component.

This is my code:

 constructor(props) {
        super(props);

        this.state = {
            text: '',
        };
    }

    nav = DrawerNavigator({
            Child: {
                screen: Child,
                navigationOptions: {
                    title: 'Child Component'
                }
            },
            Profile: {
                screen: Profile
            },
        }, {
            screen: Profile,
            contentComponent: DrawerContent
        });

       const DrawerContent = (props) => (
            <View> {this.state.text}</View>
})

    const
    nav2= DrawerNavigator({
        Child: {
            screen: Child,
            navigationOptions: {
                title: 'Child cmp'
            }
        },
        Profile: {
            screen: Profile
        },
        screen: Manager
        }
    }, {
        screen: Profile,
        contentComponent: DrawerContent
    });

    const Layout = createRootNavigator(signedIn);

    return (
        <View>
           <Layout/>
        </View>
    );

I want so when a button on Child cmp is clicked i am calling a function within the Child cmp which does some backend call after that call finishes, I want the Parent state to update. I tried different ways, but I couldnt succeed!

回答1:

If you need to update the parent state, you will need to create a function in the parent that updates its state and pass that function to the child as a prop. Then you can update the parent state by calling this.props.whateveryourmethodis