首页 > 解决方案 > 导航到另一个页面传递变量

问题描述

我对 React Native 很陌生。我有以下页面,它从数据库中加载日期和结果,所有显示都正常:

import React, { useEffect, useState } from "react";
import {
  Text,
  FlatList,
  StyleSheet,
  TouchableOpacity,
  Platform,
} from "react-native";
import AsyncStorage from "@react-native-community/async-storage";
import Colors from "../../../res/Colors/Colors";
import { s, scale } from "react-native-size-matters";
import Axios from "axios";
import moment from "moment";
import { SafeAreaView} from "react-navigation";


export default function HistoryScreen({ navigation }) {
  
  const [userDetails, setUserDetails] = useState(null);
  const [loading, setLoading] = useState(true);
  const [Star, setStar] = useState(null);

  const [people, setPeople] = useState(null);

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

  const expandMonth  = (month,year) => {
    console.log(month);
    console.log(year);
  }



  const _getHistory = async () => {
    let star = await AsyncStorage.getItem("star");
    star = JSON.parse(star);
    setStar(star);
    var formData = new FormData();
    formData.append("StarID", star.StarID);
    Axios({
      method: "post",
      url: "**API URL**",
      data: formData,
      //headers: { "Content-Type": "multipart/form-data" },
    })
    .then(async (response) => {
        var responseBody = response.data.detail;
        setPeople(responseBody);
        setLoading(false);
    })
    .catch((error) => {
      console.log({ error });
    });
  };

  if (loading)
  return (
    <SafeAreaView>
    </SafeAreaView>
  );
  return (
    <SafeAreaView
      style={{
        flex: 1,

        backgroundColor: Colors.lightGrey,
        paddingTop: Platform.OS === "android" ? 40 : 40,
        justifyContent: "space-evenly",
      }}
    >

    <Text style={styles.headerText}>History</Text>

    <FlatList
      //keyExtractor={(item) => item.id}
      data={people}
      renderItem={({ item }) => (
        <TouchableOpacity onPress={() => {
            expandMonth(item.Month,item.Year)
            navigation.navigate("HistoryMonthScreen", {
            Month: item.Month,
            Year: item.Year
            });
        }}
        style={styles.month}>
        <Text style={styles.monthname}>{moment(item.Month, 'M').format('MMMM')} {item.Year}</Text>
        <Text style={styles.monthcount}>{item.Count} Bookings</Text>
        </TouchableOpacity>
      )}
    />      


    </SafeAreaView>
  );
}

但是,当单击该TouchableOpacity对象时,它不会导航到传递年份和月份变量的下一页。我假设我需要调用某种形式的导航,但是我尝试过的一切都导致了一个又一个错误。

标签: react-native

解决方案


对于 React Navigation 5,您必须使用route旁边传递的道具来navigation导航到您要导航到的任何屏幕。

将以下代码放入HistoryMonthScreen.js

const HistoryMonthScreen = ({route, navigation}) => {
    console.log(route.params.Month, route.params.Year);
    return <View />
}

编辑:对于上下文:

我要离开你在这里的东西

navigation.navigate("HistoryMonthScreen", {
            Month: item.Month,
            Year: item.Year
            });

所以我假设你在某个地方有一些 React Navigator,看起来像这样:

const AppNavigator5 = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator
        initialRouteName="HistoryScreen"
        screenOptions={{
          headerShown: false,
          animationEnabled: false,
        }}>
        <Stack.Screen
          name="HistoryScreen"
          component={HistoryScreen}
        />
        <Stack.Screen
          name="HistoryMonthScreen"
          component={HistoryMonthScreen}
        />
        <Stack.Screen name="Egg" component={Egg} />
      </Stack.Navigator>
    </NavigationContainer>
  );
};

您将代码与route该组件一起navigation放入该HistoryMonthScreen组件中。您可以将不同的参数传递给route.params每次,您不必更改 HistoryMonthScreen。


推荐阅读