如何在 React Native 组件树中将一个组件导航到另一个组件?

时间:2021-04-05 21:18:37

标签: javascript react-native react-navigation

我已经实现了 2 个组件,以下是组件树。

我的购买 <--- 产品卡 (父母)(孩子)

我需要从 productCard 组件按钮导航到另一个名为“complainytSubmission”的屏幕

但是它说 navigation.navigate 不是函数,并且 undefined 不是函数,我该如何解决?

“我的购买”组件:

mport * as React from 'react';
import {Dimensions, StyleSheet, View, FlatList, ScrollView, TouchableOpacity} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import {Card, Button, Text} from 'react-native-paper';
import {useEffect, useState} from 'react';
import AsyncStorage from '@react-native-community/async-storage';
import ProductCard from './ProductCard';
import LinearGradient from "react-native-linear-gradient";
import {hostName} from '../../constants/constants';

const MypurchaseSceen = ({navigation}) => {
  const [productDetails , setproductDetails] = useState([]);
  console.log('productDetails Array',productDetails);

  useEffect(() => {
    getProductDetails();
  }, []);


  const getProductDetails = async () => {
    const token = await AsyncStorage.getItem('userToken');
    console.log('token from storage', token);

    fetch(hostName +"/customer/get-all-products", {

      method: "post",
      headers: {
        'Content-Type': 'application/json',
        'Authentication': `Bearer ${token}`
      },
    })
        .then((response) => response.json())
        .then((json) => setproductDetails(json))
        .catch((error) => console.error(error))

  };


  return (
      <View>
          <FlatList data={productDetails.data}
                    keyExtractor={( item ,index) => 'key' + index}
                    renderItem={({item}) => {
                      return (
                          <ProductCard item = {item}/>
                      
                          )
                    }} />
        
        
      </View>
  );
};
export default MypurchaseSceen;

产品卡组件:

import * as React from 'react';
import {Dimensions, StyleSheet, TouchableOpacity, View} from 'react-native';
import { Text} from 'react-native-paper';
import LinearGradient from "react-native-linear-gradient";
import ProductButton from './ProductButton';

const ProductCard = ({item} )=> {

    return (
        <View>
            <View style={ styles.cardView}>

                <Text style={styles.productName}> Product Name :{item.productName}</Text>
                <Text style={styles.category}> Category :{item.category} </Text>
                <ProductButton />

            </View>
        </View>
    );
};
export default ProductCard;

1 个答案:

答案 0 :(得分:1)

在您的 ProductButton 中,尝试使用导航钩子

export function ProductButton(){
   const navigation = useNavigation();


  return(
    <Button onClick={() => navigation.navigate('complainytSubmission')}
 )
}