如何在React组件的函数之间传递道具

时间:2019-11-14 04:31:44

标签: reactjs react-native react-navigation react-props

我希望将prop传递给导航选项标题中的组件。有没有一种方法可以从组件内部将itemId传递到SaveButton,而无需使用上下文API或Redux?

export default PostingDetail = ({ navigation }) => {
    const itemId = navigation.getParam('itemId', null)
    return (
        <SafeAreaView >
        </SafeAreaView>
    )
}

PostingDetail.navigationOptions = ({ navigation }) => ({
    title: "Posting Detail",
    headerRight: (
        <PleaseSignIn navigation={navigation} >        
            <SaveButton id={itemId} />
        </PleaseSignIn>
    )
})

1 个答案:

答案 0 :(得分:1)

您可以按以下方式传递参数:

export default PostingDetail = ({ navigation }) => {
    const itemId = navigation.getParam('itemId', null);
    navigation.setParams({ itemId }); // Pass itemId to navigation state
    return (
        <SafeAreaView >
        </SafeAreaView>
    )
}

然后您将获得itemId,如下所示:

PostingDetail.navigationOptions = ({ navigation }) => ({
    title: "Posting Detail",
    headerRight: (
        <PleaseSignIn navigation={navigation} >        
            <SaveButton id={navigation.state.params.itemId} />
        </PleaseSignIn>
    )
})