[英]How to properly type navigation passed as props with React-Navigation with expo
如何正確鍵入作為道具傳遞給另一個組件的導航? 根據文檔
應用程序中的每個屏幕組件都會自動提供導航道具。
並且,
要對屏幕進行類型檢查,我們需要對屏幕接收到的導航道具和路線道具進行注釋。
type Props = NativeStackScreenProps<RootStackParamList, 'Profile'>;
我有一個帶路由器的導航組件:
const App: React.FC = () => {
const [userMetrics, setUserMetrics] = useState<UserMetrics>(null);
const Stack = createNativeStackNavigator<RootStackParamList>();
return (
<UserMetricsContext.Provider value={{ userMetrics, setUserMetrics }}>
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={Home} />
<Stack.Screen name="Tests" component={Tests} />
</Stack.Navigator>
</NavigationContainer>
</UserMetricsContext.Provider>
);
};
在主屏幕中,我想接收導航道具以將其進一步傳遞給表單,該表單有一個按鈕,該按鈕將導航到測試組件並將表單數據作為參數傳遞:
interface Props {
navigation: NativeStackScreenProps<RootStackParamList, "Home">;
}
export const Home: React.FC<Props> = ({ navigation }) => {
const { setUserMetrics } =
useContext<IUserMetricsContextType>(UserMetricsContext);
return (
<View style={styles.container}>
<StatusBar style="auto" />
<HealthCheckForm onSubmit={setUserMetrics} navigation={navigation} />
</View>
);
};
現在問題開始在表單組件中可見,因為 typescript 假設一個級別太多,我已經像在父 Home 組件中那樣輸入了道具,如下所示:
interface Props {
onSubmit: React.Dispatch<React.SetStateAction<UserMetrics>>;
navigation: NativeStackScreenProps<RootStackParamList, "Home">;
}
和 typescript 希望我像這樣使用它:
const submitHandler = (data: UserMetrics) => {
onSubmit(data);
navigation.navigation.navigate("Tests", { userMetrics: data });
console.log(data);
};
但是,這不起作用,正確的-工作和導航用法是
navigation.navigate("Tests", { userMetrics: data });
當我導航到 Tests 組件並傳遞參數時,我不知道如何在 Test 組件中接收它們。 我試圖像這樣類比地做到這一點:
interface Props {
navigation: NativeStackScreenProps<RootStackParamList, "Tests">;
}
export const Tests: React.FC<Props> = ({ navigation }) => {
const { userMetrics } =
useContext<IUserMetricsContextType>(UserMetricsContext);
console.log({ params: navigation.route.params });
return (
<View>
<DisplayList />
</View>
);
};
而且我收到另一個關於讀取未定義屬性的錯誤。 謝謝
有嵌套導航器的解決方案(這里的起點: https://reactnavigation.org/docs/nesting-navigators/ )。 但是,在這種情況下,我建議不要讓您的HealthCheckForm
了解導航 state。 只需將標准onSubmit()
傳遞給它並處理Home
組件中的所有導航。
另外作為提示,請確保正確設置您的RootStackParamList
,以便“測試”路線期待{userMetrics: YourDataType}
。 這是設置它的一個隨機示例。
export type RootStackParamList = {
myRouteName: undefined;
tests: { userMetrics: MyDataType }; // TS now expects MyDataType on the props for tests route
terminalAndMate: {
departingTerminal: WSFTerminal;
arrivingTerminal: WSFTerminal;
};
...
我還建議以這種方式輸入屏幕道具,而不是作為界面。 NativeStackScreenProps 可以攜帶 rootStackParamList 中定義的參數:
type TestsScreenProps = NativeStackScreenProps<RootStackParamList, "tests">;
通過這兩個更改, tests
屏幕應該有props.route.params
,其中將包含 MyDataType。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.