【问题标题】:How to pass parameters to a component in another screen in Stack Navigation in react-native?如何在 react-native 的 Stack Navigation 中将参数传递给另一个屏幕中的组件?
【发布时间】:2019-03-12 07:01:44
【问题描述】:

我有一个索引页面,其中有一个用户列表,如果用户点击每个用户,它会转到他们的个人资料屏幕,我可以传递 id 来呈现个人资料屏幕,但问题是个人资料页面由几个components ,我需要在组件中使用接收到的数据。

这是我将数据传递给用户个人资料的方式:

onPress={() => this.props.navigation.navigate('userProfile',{item})}>

这是我在 userProfile 中接收它的方式:

    export default class UserProfileScreen extends React.Component {

      render() {
        const {item} = this.props.navigation.state.params;
        return (
          <ScrollView>
            <View style={styles.container}>
              <IntroCard item={item}/>
            </View>
          </ScrollView>
}
}

这就是我在&lt;IntroCard&gt; 组件中接收数据的方式:

const IntroCard = (props) => {
  return (
    <View>
       <Text>{this.props.item ? this.props.item.id : 'default'}</Text>
    </View>
)}

但在完成所有这些操作后,我收到以下错误:

TypeError: TypeError: TypeError: undefined is not an object (evaluating '_this.props.item')

【问题讨论】:

标签: react-native jsx


【解决方案1】:

您可以将其作为prop 传递给组件

render(){
  const {item} = this.props.navigation.state.params;
  return (
    <View>
      <Component item={item}/>
    </View>
  )
}

然后在Component 上使用this.props 访问它

<Text>{props.item ? props.item.id : 'print something else'}</Text>

【讨论】:

  • 注意参数可能未定义
  • 非常感谢。如何在组件中定义它们?
  • 更新了我的答案,你可以随时查看this.props.item
  • 或者如果你认为默认值更好,你也可以使用defaultProps。签出此SO answer
  • 抱歉打扰,但我仍然收到此错误:TypeError: undefined is not an object (evalating '_this.props.item')
猜你喜欢
  • 2018-12-30
  • 2021-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
相关资源
最近更新 更多