我正在使用 TypeScript 开发 React Native 项目,并且在使用 React Navigation 设置 BottomTabNavigator 时遇到问题。这是我的代码的相关部分:
import { createBottomTabNavigator, type BottomTabScreenProps } from '@react-navigation/bottom-tabs';
import { StackScreenProps } from '@react-navigation/stack';
import { RootStackParamList } from '.';
import { HeaderButton } from '../components/HeaderButton';
import { TabBarIcon } from '../components/TabBarIcon';
import Two from '../screens/two';
import HomeScreen from '../screens/home';
const Tab = createBottomTabNavigator();
export type TabParamList = {
TabNavigator: undefined;
Home: undefined;
Two: undefined;
};
type Props = BottomTabScreenProps<TabParamList, 'TabNavigator'>;
export default function TabLayout({ navigation }: Props) {
return (
<Tab.Navigator
screenOptions={{
tabBarActiveTintColor: 'black',
}}
>
<Tab.Screen
name="Home"
component={HomeScreen} //error on this line
options={{
headerShown: false,
tabBarIcon: ({ color }) => <TabBarIcon name="home" color={color} />,
headerRight: () => <HeaderButton onPress={() => navigation.navigate('Modal')} />,
}}
/>
<Tab.Screen
name="Two"
component={Two}
options={{
title: 'Agendamentos',
tabBarIcon: ({ color }) => <TabBarIcon name="folder" color={color} />,
}}
/>
</Tab.Navigator>
);
}
HomeScreen组件定义如下:
import { useEffect, useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { BottomTabScreenProps } from '@react-navigation/bottom-tabs';
import type { TabParamList } from '../navigation';
type HomeScreenProps = BottomTabScreenProps<TabParamList, 'Home'>;
export default function HomeScreen({ route }: HomeScreenProps) {
const [bookings, setBookings] = useState([]);
useEffect(() => {
const fetchBooking = async () => {
try {
const response = await fetch('http://example.com/booking/');
const data = await response.json();
setBookings(data);
} catch (error) {
console.error(error);
}
};
fetchBooking();
}, []);
return (
<SafeAreaView style={styles.mainContainer}>
<View>
<Text>{route.name}</Text>
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
mainContainer: {
flex: 1,
backgroundColor: 'white',
},
});
但是,在 Tab.Navigator 中使用 HomeScreen 组件时,出现以下 TypeScript 错误:
Type '({ route }: HomeScreenProps) => Element' is not assignable to type 'ScreenComponentType<ParamListBase, "Home"> | undefined'.
Type '({ route }: HomeScreenProps) => Element' is not assignable to type 'FunctionComponent<{}>'.
Types of parameters '__0' and 'props' are incompatible.
Type '{}' is missing the following properties from type 'HomeScreenProps': navigation, route
我已确认 TabParamList 包含“Home”路线,并且 HomeScreenProps 正确键入为
BottomTabScreenProps<TabParamList, 'Home'>
。
我不知道为什么错误提示导航和路线丢失,而它们明确包含在道具中。
对于如何解决这个问题有什么建议吗?预先感谢!
需要注释
createBottomTabNavigator
const Tab = createBottomTabNavigator<TabParamList, 'TabNavigator'>();
https://reactnavigation.org/docs/typescript/?config=dynamic#typechecking-the-navigator