You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

向React组件传递参数失败:Expo报错排查请求

解决React Navigation中组件传参的Invalid 'component' Prop错误

错误原因

你遇到的报错:

Got an invalid value for 'component' prop for the screen 'Student1'. It must be a valid React Component.

根源在于StudentListDrawer.Screen的component属性配置错误——你直接调用了StudentScreen({studentName: 'Julia'}),这会立即执行组件并返回JSX元素,而非传递一个有效的React组件引用。

修复方案

方案1:使用initialParams传递参数(推荐)

这是React Navigation官方推荐的传参方式,既符合规范又能保证组件复用性:

修改StudentsScreen中的屏幕配置,通过initialParams传递参数:

function StudentsScreen({ navigation }) {
    const dimensions = useWindowDimensions();

    return (
        <StudentListDrawer.Navigator
            screenOptions={{
                drawerType: dimensions.width >= 768 ? 'permanent' : 'slide',
            }}>
          <StudentListDrawer.Screen
            name='Student1'
            component={StudentScreen}
            initialParams={{ studentName: 'Julia' }}
          />
          <StudentListDrawer.Screen
            name='Student2'
            component={StudentScreen}
            initialParams={{ studentName: 'Samuel' }}
          />
        </StudentListDrawer.Navigator>
    )
}

调整StudentScreen,通过route.params获取参数:

function StudentScreen({ route }) {
    const studentName = route.params.studentName;

    return (
        <View>
          <Text>The student's name is {studentName}</Text>
        </View>
    )
}

方案2:使用包装组件动态传参

如果需要更灵活的参数传递,可以用一个函数返回组件实例:

function StudentsScreen({ navigation }) {
    const dimensions = useWindowDimensions();

    return (
        <StudentListDrawer.Navigator
            screenOptions={{
                drawerType: dimensions.width >= 768 ? 'permanent' : 'slide',
            }}>
          <StudentListDrawer.Screen
            name='Student1'
            component={() => <StudentScreen studentName='Julia' />}
          />
          <StudentListDrawer.Screen
            name='Student2'
            component={() => <StudentScreen studentName='Samuel' />}
          />
        </StudentListDrawer.Navigator>
    )
}

注意:这种方式下,每次切换到该屏幕都会重新挂载组件,若组件有状态或副作用需要持久化,建议优先用方案1。

关键注意点

  • component属性必须接收组件本身(函数或类),而不是组件执行后的JSX结果。
  • 使用initialParams传递的参数,会被合并到屏幕的route.params中,可在组件内直接访问。

内容的提问来源于stack exchange,提问作者Matthew Chisolm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 19:27:23