Typescript StackNavigatonReact导航v5中的道具和屏幕道具



当屏幕位于路由器的不同文件中时,定义屏幕navigation道具类型的最佳方法是什么?假设我有一个文件,在其中我定义了路由:

//Router.tsx
type RootStackParamList = {
Home: undefined;
Profile: undefined;
}
const Stack = createStackNavigator<RootStackParamList>();
// Component rendering navigator
const Router = () => {
.
.
.
}

然后我有一个单独的屏幕文件:

// Home.tsx

// here has to be the same RootStackParamList
// that we've already defined in Router.tsx
type = HomeScreenNavigationProp = StackNavigationProp<
RootStackParamList,
"Home"
>;
type Props: {
navigation: HomeScreenNavigationProp
}

const Home = ({navigation}: Props) => {
.
.
.
}

我是否必须将RootStackParamList一遍又一遍地复制到每个屏幕,或者创建类似types.ts的文件并从那里导入?有更好的方法处理它吗?我几乎在每个组件中都使用navigation

你可以试试这个:

type RootStackComponent<RouteName extends keyof RootStackParamList> = React.FC<
navigation: StackNavigationProp<RootStackParamList, RouteName>,
route: RouteProp<RootStackParamList, RouteName>
>
const Home: RootStackComponent<'Home'> = ({ navigation, route }) => {}

首先定义您的createStackNavigator类型,如下所示:

export type RootStackParamList = {
Home: undefined;
Register: undefined;
Login: undefined;
};
const Stack = createStackNavigator<RootStackParamList>();

然后转到Home.tsx组件并添加此行:

type Props = StackScreenProps<RootStackParamList, 'Home'>;
const Home = ({navigation, route}: Props) => {
.
.
. 
} 

参考:https://reactnavigation.org/docs/typescript/

最新更新