我创建自定义标头:
const header = ({ navigation, route, options, back }: NativeStackHeaderProps): React.ReactNode => {
const buttons: HeaderRightButtons = route.params?.rightButtons || []
return (...)
}
Typescript显示错误:
属性'rightButtons'在类型'object'上不存在
在此属性中;按钮":
type HeaderRightButtons = Array<{ icon: any, action: () => void }>
我尝试制作扩展类型:
export type NativeStackHeaderPropsCustomRight =
(NativeStackHeaderProps & {
route: RouteProp<{params?: { rightButtons: HeaderRightButtons }}, 'params'>
}) | NativeStackHeaderProps
但这并不能解决问题。
属性"右按钮";不存在于";object|(object&只读<{rightButtons:HeaderRightButtons;}>("类型";右按钮";属性不存在于";对象";类型
如果没有| NativeStackHeaderProps
,则在屏幕声明中显示错误:
<Stack.Screen ... options={{
header: headerMain,
title: strings.titleEpochs
}} />
类型"({导航、路线、选项、后退}:NativeStackHeaderPropsCustomRight(=>React.RreactNode";不能分配给类型";(道具:NativeStackHeaders道具(
如何编写正确的类型?
或者有更正确的方法将对象通过属性传递到自定义标头吗?
我遇到了同样的错误,我用这种方式解决了:
首先,请确保您创建了NativeStackNavigator,指定了路由对象
type RouteParamList = {
myScreenName: {
rightButtons: Array<{ icon: any, action: () => void }>
}
}
const Stack = createNativeStackNavigator<RouteParamList>();
然后,将屏幕传递函数声明为options
属性:
<Stack.Screen
name="myScreenName"
component={MyScreenComponent}
options={({ route }) => ({
header: (props) => <HeaderMain {...props} rightButtons={route.params.rightButtons} />,
})}
/>
因此,在您的HeaderMain组件中:
type NativeStackHeaderPropsCustomRight = NativeStackHeaderProps & {
rightButtons: Array<{ icon: any, action: () => void }>
};
const HeaderMain = ({ navigation, route, options, back }: NativeStackHeaderPropsCustomRight) : React.ReactNode => {
// your component here
const buttons: Array<{ icon: any, action: () => void }> = route.params?.rightButtons || []
return (...)
}
export {HeaderMain}