Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
526 views
in Technique[技术] by (71.8m points)

javascript - Pass props from child to parent react navigation

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: ..., ...})}
        ..../>
       )
    }
}

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>
       )
    }
}

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>
       )
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...