Pass props from child to parent react navigation

前端 未结 1 389
暗喜
暗喜 2020-11-27 23:37

I am using react-navigation. I am passing propsfrom a react-native component to the modal from react-navigation

相关标签:
1条回答
  • 2020-11-28 00:19

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

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

    Example

    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>
           )
        }
    }
    
    0 讨论(0)
提交回复
热议问题