如何在反应本机中获取参数

时间:2020-11-12 18:44:21

标签: react-native react-native-android react-navigation

我想将参数传递给视图。我遵循了一些示例,但无济于事。我该怎么办?

我的代码的一部分:

首页:

import React from 'react';
import { MaterialIcons } from '@expo/vector-icons';
import { useNavigation } from '@react-navigation/native';
import { View, Text, Image, StyleSheet, ScrollView } from 'react-native';

import colors from '../../components/colors';
import Shoe from '../../components/home/shoe';
import Teste from '../teste';
import Detail from '../detail';

export default function Home(props) {
    return(
        <View style={styles.storeProducts_line}>
            <Shoe 
               source={require('../../images/home/tenisAdidasFalconFeminino.jpg')}
               title="Tênis Adidas Falcon Feminino"
               price="200,00"

               onClick={() => props.navigation.navigate('Detail', {
                   productId: 12,
                   productTitle: 'Tênis Adidas',
               })}
            />
            <Shoe 
               source={require('../../images/home/tenisAdidasYeezySalt.jpg')}
               title="Tênis Adidas Yeezy Salt"
               price="175,90"
               onClick={() => navigation.navigate('Detail')}
            />
        </View>
    );
}

详细信息:

import React from 'react';
import { View, Text, StyleSheet, ScrollView, Image } from 'react-native';

export default function Detail({props, navigation}) {

   const productId = navigation.getParam('userId');
   // const productId = props.navigation.getParam('userId');

   return(
      <View style={styles.container}>
          <Image 
          />
          <Text>
              Detail
          </Text>
          <Text>
              {productId}
          </Text>
      </View>
   );
}

我看到的所有示例的视图结构都不同,是否必须更改结构才能工作?我是本机反应的新手,请多多包涵。预先感谢您的关注。

1 个答案:

答案 0 :(得分:2)

您还可以使用route访问来自父组件的传递数据。

示例:


import React from 'react';
import { View, Text, StyleSheet, ScrollView, Image } from 'react-native';

export default function Detail({route, navigation}) {

   const {productId} = route.params;
   // const productId = props.navigation.getParam('userId');

   return(
      <View style={styles.container}>
          <Image 
          />
          <Text>
              Detail
          </Text>
          <Text>
              {productId}
          </Text>
      </View>
   );
}

有关更多信息,请阅读以下文档:Passing parameters to routes