#react-native #react-navigation #react-native-paper
Вопрос:
Каков правильный и профессиональный способ с учетом лучших практик использовать централизованные маршруты, как это App.tsx
предусмотрено в компоненте BottomNavigation?
В настоящее время у меня есть подделка «маршрута» внутри компонента BottomNavigation, однако я хотел бы использовать маршруты, которые находятся в корне ( App.tsx
) в этом компоненте. Как я могу поступить с этим?
Приложение.tsx
import "react-native-gesture-handler";
import React from "react";
import { DefaultTheme, Provider as PaperProvider } from "react-native-paper";
import { NavigationContainer } from "@react-navigation/native";
import { createStackNavigator } from "@react-navigation/stack";
// SCREEN'S
import HistoryScreen from "./components/screens/HistoryScreen";
import InvestmentScreen from "./components/screens/InvestmentScreen";
import PositionScreen from "./components/screens/PositionScreen";
import QuotationScreen from "./components/screens/QuotationScreen";
import UtilScreen from "./components/screens/UtilScreen";
// GLOBAL COMPONENT'S
import NavigationBottom from "./components/globals/NavigationBottom";
import AppbarHeader from "./components/globals/AppbarHeader";
const Stack = createStackNavigator();
export default function App() {
return (
<PaperProvider theme={theme}>
<NavigationContainer>
<Stack.Navigator
initialRouteName="Quotation"
screenOptions={{ header: (props) => <AppbarHeader {...props}/> }}
>
<Stack.Screen options={{ headerTitle: "Cotações" }} name="Quotation" component={QuotationScreen} />
<Stack.Screen options={{ headerTitle: "Histórico" }} name="History" component={HistoryScreen} />
<Stack.Screen options={{ headerTitle: "Investimentos" }} name="Investments" component={InvestmentScreen} />
<Stack.Screen options={{ headerTitle: "Posição" }} name="Position" component={PositionScreen} />
<Stack.Screen options={{ headerTitle: "Utilidades" }} name="Utilities" component={UtilScreen} />
</Stack.Navigator>
<NavigationBottom />
</NavigationContainer>
</PaperProvider>
);
}
Навигация внизу.tsx
import * as React from 'react';
import { BottomNavigation, Text, useTheme } from 'react-native-paper';
const NavigationBottom = () => {
const theme = useTheme();
const [index, setIndex] = React.useState(0);
const [routes] = React.useState([
{ key: 'quotation', title: 'Cotações', icon: 'finance' },
{ key: 'history', title: 'Histórico', icon: 'history' },
{ key: 'investments', title: 'Investimentos', icon: 'chart-pie' },
{ key: 'position', title: 'Posição', icon: 'wallet' },
{ key: 'utilities', title: 'Utilitários', icon: 'tools' },
]);
const renderScene = BottomNavigation.SceneMap({
quotation: () => <Text>Cotação Route</Text>,
history: () => <Text>Histórico Route</Text>,
investments: () => <Text>Histórico Route</Text>,
position: () => <Text>Investimentos Route</Text>,
utilities: () => <Text>Utilitario Route</Text>,
});
return (
<BottomNavigation
activeColor={theme.colors.accent}
navigationState={{ index, routes }}
onIndexChange={setIndex}
renderScene={renderScene}
/>
);
};
export default NavigationBottom;
Ответ №1:
Вы можете использовать RouteProp
из @react-navigation/native
:
Приложение.tsx
export type RouteStackParamList = {
Start: undefined;
Login: { param: string };
Admin: undefined;
};
const App: FunctionComponent = () => {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Start">
<Stack.Screen name="Start" component={ClickToStartPage} />
<Stack.Screen name="Login" component={LoginPage} />
<Stack.Screen name="Admin" component={AdminPage} />
</Stack.Navigator>
</NavigationContainer>
);
};
Войдите в систему.tsx
export type MyRouteProp = RouteProp<RouteStackParamList, 'Login'>; // from app.tsx
interface LoginProps {
route: RouteProp;
}
const Login: FunctionComponent<LoginProps> = (props) => {
const { route } = props;
route.params.param; // if you need a param
route.name; // "Login"
...
}
Для более «чистой» архитектуры кода у вас может быть интерфейс между App.tsx и Login.tsx
Приложение.tsx
export enum Routes {
START = 'Start',
LOGIN = 'Login',
ADMIN = 'Admin',
}
{...}
<Stack.Screen name=Routes.START component={ClickToStartPage} />
<Stack.Screen name=Routes.LOGIN component={LoginPage} />
<Stack.Screen name=Routes.ADMIN component={AdminPage} />
Войдите в систему.tsx
export type MyRouteProp = RouteProp<RootStackParamList, Routes.LOGIN>;
Комментарии:
1. Хорошо, но при чем здесь AppbarHeader и NavigationBottom, поскольку они являются глобальными компонентами?