将props从子级传递给父级react导航

IT技术 javascript react-native router react-navigation
2021-02-19 21:42:30

我正在使用react-navigation. 我正在props从 a传递react-native component到在水龙头上打开modalfrom react-navigation

export default class SomeComp extends Component {
...

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

modalI内部访问goBack()关闭函数modal,以及props通过的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 下来ModalSomeComp没有使用redux在“正常”情况下,react-native parent-child component我会用一个简单的callback. 但是,这在这里不起作用,因为modal是在 中定义的router,因此完全独立于SomeComp它只是从那里调用...

1个回答

有一个非常简单的解决方案可以将 props 传回goBack().

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

例子

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>
       )
    }
}
哦,天哪...我没想过将 afunction作为prop通过params...谢谢!
2021-04-26 21:42:30
如果将函数作为参数传递,则会收到警告,因为它们不可序列化。这里有更多信息以及如何关闭警告reactnavigation.org/docs/troubleshooting/...
2021-05-04 21:42:30