在大多数情况下,我遵循一个简单的模式,在react导航v5下输入任何屏幕:
// Params definition
type RouteParamsList = {
Screen1: {
paramA: number
}
Screen2: undefined
}
// Screen1
type Props = StackScreenProps<RouteParamsList, 'Screen1'>
export const Screen1: React.FC<Props> = ...这很好用。
但是,当我想要为不同的导航器重用Screen1时,我找不到合适的类型:
// Params definition
type RouteParamsListShop = {
Screen1: {
paramA: number
}
Screen2: undefined
Screen3: undefined
}
type RouteParamsListFeatures = {
Screen1: {
paramA: number
}
Screen4: undefined
}
// Screen1
type Props = StackScreenProps<RouteParamsListShop, 'Screen1'> | StackScreenProps<RouteParamsListFeatures, 'Screen1'> // Tried this
export const Screen1: React.FC<Props> = ...正如我所说的,我尝试使用一个能涵盖这两种情况的联合类型。它允许从路由正确获取参数,但navigate方法中断:
This expression is not callable. Each member of the union type '/* Route info here */' has signatures, but none of those signatures are compatible with each other.ts(2349)
有没有一种方法可以正确地输入它,或者我必须改变导航的结构,使屏幕只是一条路线的一部分?(或者,为不同的导航创建两个包装器)。
发布于 2021-02-20 08:21:44
这里有一个更基本的问题,而不仅仅是正确地键入联合。如果我们的navigation属性是针对RouteParamsListShop的,那么我们可以导航到Screen2。如果我们的navigation属性是针对RouteParamsListFeatures的,那么我们就不能这样做,因为Screen2没有在该堆栈上定义。所以有一种内在的不兼容性。
你是否曾经试图从Screen1导航到另一个同时在两个屏幕上声明的屏幕?如果是这样的话,我们可以输入它。如果不是,那么您就有了设计问题。
您需要的不是一个联合,而是一个既包括目标屏幕又包括当前屏幕的共享子集。我们可以使用一些帮助器类型来简化这一过程。
type SharedKeys = keyof RouteParamsListShop & keyof RouteParamsListFeatures
// we Pick from both instead of just one in case the params are different
type SharedParams = Pick<RouteParamsListShop, SharedKeys> & Pick<RouteParamsListFeatures, SharedKeys>
type Props = StackScreenProps<SharedParams, 'Screen1'>这允许您调用navigation.navigate --但仅当导航到在两种堆栈类型中定义的屏幕时。在您的示例中,没有留下可供我们导航的屏幕,但在您的实际情况下,可能会有可用的导航目标。
https://stackoverflow.com/questions/65422185
复制相似问题