【问题标题】:Passing param to route React native传递参数来路由 React Native
【发布时间】:2020-06-11 17:17:25
【问题描述】:

我正在尝试将参数传递到新屏幕以显示它。我的对象在我使用地图显示的数组的获取数据中,代码如下所示:

 <Text > Show:</Text>
{
                        this.state.data.map((item, i) => {
                            //Show only two dates 
                            return (i < 2) ?
                                <View>
                                    <Text>{moment(item[0]).format("ddd DD/MM")}</Text>
                                    <View style={{ flex: 1, flexDirection: 'row' }}>
                                        {
                                            item[1].map((day, i) => {
                                                //show only 3 times
                                                return (i < 3) ?
                                                <TouchableOpacity onPress={() => NavigationService.navigate('myScreen',//what should i wright here!>
                                                    <Text>{moment(day.date_start).format("h:mm a")}</Text> // i want to pass this displayed text {moment(day.date_start).format("h:mm a")}
                                                    </TouchableOpacity>
                                                    :
                                                    <></>
                                            })
                                        }
                                    </View>
                                </View>
                                : <></>

                        })
                    }

如您所见,我想将 {moment(day.date_start).format("h:mm a")} 传递给 myScreen 并显示它,但我不知道如何。 myScreen 代码很简单:

class Myscreen extends React.Component {


  render() {

    return (
<Text>  display it here!   </Text>

我会很感激一些帮助。谢谢

【问题讨论】:

  • 您使用的导航库是什么?和 NavigationService 还是 Navigation ?
  • 我正在使用最新版本的 react-navigation-stack": "^2.1.1"
  • @AymenAymen 我认为您必须将您的版本升级到 ^5.x.x。示例:“@react-navigation/stack”:“^5.2.14”

标签: react-native ecmascript-6 stack-navigator


【解决方案1】:

在您的第一个屏幕中,您必须像这样传递文本...

<TouchableOpacity onPress={() => this.props.navigation.navigate('myScreen', { text: moment(day.date_start).format("h:mm a") })}>
  <Text>Press me</Text>
</TouchableOpacity>

在您的 myScreen 中,您必须像这样接收它...

class Myscreen extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    const text = this.props.route.params.text;
    return (
      <Text>{text}</Text>
    )
  }
}

请确保您使用的是@react-navigation/stack": "^5.x.x

【讨论】:

  • 是的,我愿意 "@react-navigation/stack": "^5.0.3",谢谢你的回答!
猜你喜欢
  • 2021-11-03
  • 2021-01-05
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 2016-11-07
  • 1970-01-01
  • 1970-01-01
  • 2021-08-13
相关资源
最近更新 更多