将道具从子级传递给父级反应导航 [英] Pass props from child to parent react navigation

查看:38
本文介绍了将道具从子级传递给父级反应导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 react-navigation.我将 propsreact-native 组件 传递到 react-navigationmodal点按.

I am using react-navigation. I am passing propsfrom a react-native component to the modal from react-navigation which is opened on a tap.

export default class SomeComp extends Component {
...

render() {
    const { navigate } = this.props;
    return (
        <TouchableOpacity
        onPress={navigate("Modal", {data: ..., ...})}
        ..../>
       )
    }
}

modal 中,我访问了 goBack() 函数,它关闭了 modal 以及 props> 通过 SomeComp

Inside the modal I access the goBack() function which closes the modal, as well as the props passed through SomeComp

export default class Modal extends Component {
...

render() {
    const { data, ... } = this.props.navigation.state.params;
    const { goBack } = this.props.navigation;
    return (
        <View>
            <TouchableOpacity
            onPress={goBack()}
            ..../>
            <Text>
               {data, ...}
            </Text>
        </View>
       )
    }
}

我想知道的是,是否可以将 props downModal 传递到 SomeComp没有使用redux.在普通"react-native 父子组件 中,我会用一个简单的callback 来做到这一点.但是,这在这里不起作用,因为 modal 是在 router 中定义的,因此完全独立于 SomeComp.它只是从那里调用...

What I wonder is, whether its possible or not to pass props down from Modal to SomeComp, without using redux. In a "normal" react-native parent-child component I would do that with a simple callback. However, that does not work here, because the modal is defined in the router, hence, completely independent from SomeComp. Its only called from there...

推荐答案

goBack() 上将 props 传回父组件有一个非常简单的解决方案.

There is really simple solution to pass back props to parent component on goBack().

您可以在调用 goBack() 之前或在 componentWillUnmount 中将包含函数的额外道具传递给 Modal,您可以调用该函数.

You can pass an extra prop containing function to Modal and right before calling goBack() or in componentWillUnmount you can call that function.

示例

export default class SomeComp extends Component {
...

onGoBack = (someDataFromModal) => {
  console.log(someDataFromModal);
}

render() {
    const { navigate } = this.props;
    return (
        <TouchableOpacity
        onPress={navigate("Modal", {data: ..., ..., onGoBack: this.onGoBack})}
        ..../>
       )
    }
}

<小时>

export default class Modal extends Component {
...

componentWillUnmount() {
  if(this.props.navigation.state.params.onGoBack) {
    this.props.navigation.state.params.onGoBack('I fired from Modal!');
  } 
}

render() {
    const { data, ... } = this.props.navigation.state.params;
    const { goBack } = this.props.navigation;
    return (
        <View>
            <TouchableOpacity
            onPress={goBack()}
            ..../>
            <Text>
               {data, ...}
            </Text>
        </View>
       )
    }
}

这篇关于将道具从子级传递给父级反应导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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