paf*_*fry 7 typescript react-native react-navigation expo
navigation当屏幕与路由器位于不同的文件中时,定义屏幕道具类型的最佳方法是什么?假设我有一个文件,我在其中定义了路线:
//Router.tsx
type RootStackParamList = {
Home: undefined;
Profile: undefined;
}
const Stack = createStackNavigator<RootStackParamList>();
// Component rendering navigator
const Router = () => {
.
.
.
}
Run Code Online (Sandbox Code Playgroud)
然后我有单独的屏幕文件:
// 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) => {
.
.
.
}
Run Code Online (Sandbox Code Playgroud)
我是否必须RootStackParamList一遍又一遍地复制到每个屏幕或创建类似types.ts文件的内容并从那里导入它?有没有更好的方法来处理呢?我几乎在每个组件中都使用navigation。
小智 3
你可以试试这个:
type RootStackComponent<RouteName extends keyof RootStackParamList> = React.FC<
navigation: StackNavigationProp<RootStackParamList, RouteName>,
route: RouteProp<RootStackParamList, RouteName>
>
Run Code Online (Sandbox Code Playgroud)
const Home: RootStackComponent<'Home'> = ({ navigation, route }) => {}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10230 次 |
| 最近记录: |