React Navigation useLayoutEffect headerRight给Typescript错误

时间:2020-08-26 22:15:03

标签: typescript react-navigation

遵循React Navigation的instructions here

我的代码中有这个

useLayoutEffect(() => {
    function signOut() {
      setUser(undefined);
      navigation.navigate('Search');
    }
    navigation.setOptions({
      headerRight: () => <Button onPress={() => signOut()} title="Log out" type="clear" />,
    });
  }, [navigation, setUser]);

我收到TypeScript错误:

Argument of type '{ headerRight: () => JSX.Element; }' is not assignable to parameter of type 'Partial<BottomTabNavigationOptions>'.
  Object literal may only specify known properties, and 'headerRight' does not exist in type 'Partial<BottomTabNavigationOptions>'.

您知道为什么以及如何解决此问题吗?

1 个答案:

答案 0 :(得分:0)

问题在于您使用的导航器的类型。文档中的代码适用于堆栈或抽屉导航器。使用堆栈导航器,navigation.setOptions 的类型是:

setOptions(options: Partial<StackNavigationOptions>): void;

type StackNavigationOptions 包含声明 type StackHeaderOptionsheaderRight property

您收到错误消息,因为您使用的是具有不同类型选项的不同类型的导航器。

'headerRight' does not exist in type 'Partial<BottomTabNavigationOptions>'

那个 type BottomTabNavigationOptions 不包含任何与标题相关的类型,因为底部标签没有标题

如果要设置 headerRight 属性,则需要使用支持它的导航器类型,例如堆栈或 drawer 导航器。