【问题标题】:react native passing params to other component将本机传递参数反应给其他组件
【发布时间】:2026-01-14 02:40:01
【问题描述】:

您好,我是新来的本地人,并试图学习一些东西。我正在尝试将按钮单击上的用户名传递给子视图。这是我在按钮单击视图 A 上的代码

this.props.navigation.navigate('GetRegisteredScreen', {}, {
    type: ' Navigate',
    routeName: 'GetRegisteredScreen',
    params: {username: 'Robert'}
})

查看 B

componentDidMount(){
  alert(this.props.navigation.state.params.username)
}

遇到错误

params.username 中未定义

我做错了什么?

谁能帮忙,先谢谢了

编辑:这是我得到的this.props.navigation

【问题讨论】:

  • 如果你创建console.log(this.props.navigation),你会得到什么?
  • 我已经测试了你的代码,它运行良好。但我更改了'Navigate' 而不是' Navigate'。没有空格。
  • 当我尝试打印 console.log(this.props.navigation.state.params.username) 时,我仍然得到“未定义”。

标签: react-native components react-navigation


【解决方案1】:

我猜你的导航器会将 params 中的属性注入到下一个组件的 props 中,所以只需使用

this.props.username

【讨论】:

  • 我已经检查过了,但它仍然无法正常工作。你能给我看一个示例代码吗?
【解决方案2】:

你有一个语法错误。你传错了。它应该如下所示。

this.props.navigation.navigate({
  routeName: 'GetRegisteredScreen',
  username: 'Robert'
});
// OR
this.props.navigation.navigate('GetRegisteredScreen', {
  username: 'Robert'
});    

您使用的语法是dispatching navigate action

示例

const navigateAction = NavigationActions.navigate({
  routeName: 'Profile',
  params: {},
  action: NavigationActions.navigate({ routeName: 'SubProfileRoute'})
})

this.props.navigation.dispatch(navigateAction)

【讨论】: