如何使用 React Navigation 5 捕获参数?

How to catch params with React Navigation 5?

更新:我确实解决了这个问题,您可以在发布后不久在我的评论中看到。我会坚持下去,以防它对其他人有帮助,或者如果有人有更好的方法或方法。

我的目标是将参数传递给下一个屏幕。我将展示我是如何在没有 React Navigation 5 的情况下完成它的,这样你就可以看到我的目标:

我在一个屏幕上有一个按钮,如下所示:

<Button
    title="View Card"
    onPress={() => this.props.navigation.navigate("CardDetail", {cardId: 1})}
/>

这会将我带到另一个屏幕 CardDetail:

我显示cardId:

class CardDetail extends Component {
    render() {
        return(
            <View>
                <Text>{this.props.route.params.cardId}</Text>
                <Text>Card Detail </Text>
            </View>
        );
    }
}

现在,我已经实现了 React Navigation,但找不到捕获参数的方法。这是我拥有的:

function Overview({props}) {
    return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text>Overview</Text>
        <Text>{prop}</Text> // this doesn't work
    </View>
  );
}

const Tab = createBottomTabNavigator();

class CardDetail extends Component {
    render() {
        return(
             <Tab.Navigator>
                 <Tab.Screen name="Overview" component={Overview} />
             </Tab.Navigator>
        );
    }
}

我试过几种方法:这是一个

function Overview({props}) {
    const cardId = React.useState(this.props.route.params.cardId);
    return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text>Overview</Text>
        <Text>{cardId}</Text>
    </View>
  );
}

尝试添加:

<Tab.Screen name="Overview" component={Overview} options={{ title: this.props.route.params.cardId }} />

这个错误:label is not a function

尝试过这种方法:这似乎是最有希望的 https://reactnavigation.org/docs/hello-react-navigation/ 功能概述(道具){ const cardId = this.props.route.params.cardId; console.log("sadf", 道具); return ( 概述 {cardId} ); }

            <Tab.Screen name="Overview">
                {props => <Overview {...this.props}  />}
            </Tab.Screen>

这看起来很有希望,但我找不到真正将其传递给概述的方法。

我试过通过以下几种方式传递道具:const Tab = createBottomTabNavigator({props});。要么没有任何反应,要么它告诉我我的方法在 RN5

中不被接受

我的尝试是否正确?

我已经通读了RN5的文档并尝试了很多方法来传递参数

https://reactnavigation.org/docs/custom-navigators/

太简单了 第一:当您传递参数 CardDetail(Now is tabbar) 时,这意味着您的参数是 CardDetail

的道具
const Tab = createBottomTabNavigator();

class CardDetail extends Component {
    const cardId = this.props.route.params.cardId
    render() {
        return(
             <Tab.Navigator>
                 // ==> and pass cardId into Overview as props
                 <Tab.Screen name="Overview" component={() => <Overview cardId={cardId}/>} />
             </Tab.Navigator>
        );
    }
}

在 Overview 组件中,只需像那样使用 cardId

function Overview(props) {
    const {cardId} = props;
    return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text>Overview</Text>
        <Text>{cardId}</Text>
    </View>
  );
}