如何使用 Typescript 在无状态组件上设置 navigationOptions

How to set navigationOptions on stateless component with Typescript

我有一个像

这样的反应组件
const Example = () => (<View>...</View>);

使用 react-navigation 我通常会通过说

来应用导航选项
Example.navigationOptions = { options };

使用打字稿时出现错误

[ts] Property 'navigationOptions' does not exist on type '(props: Props) => Element'.

我该如何解决这个问题?

我试过写一个界面

interface ExampleWithNavigationOptions extends Element {
    navigationOptions?;
}

但运气不好。

关键思想是为 Example 常量指定正确的类型。可能 react-navigation 已经提供了该类型。但是,您也可以像这样扩展 build-in React 接口:

    interface NavStatelessComponent extends React.StatelessComponent {
        navigationOptions?: Object
    }

    const Example: NavStatelessComponent = () => {
        return (
            <View>
               ...
            </View>
        )
    }

    Example.navigationOptions = {
        /*
        ...
        */
    }

    Example.propTypes = {
        /*
        ...
        */
    }

如果您希望所有组件都使用相同的导航选项,请记住您可以在 createStackNavigator 中设置 defaultNavigationOptions。如果您需要示例,这里是 React Navigation API

您可以使用以下内容:

import {
  NavigationScreenProps,
  NavigationScreenComponent
} from 'react-navigation'

interface Props extends NavigationScreenProps {
  // ... other props
}

const MyScreen: NavigationScreenComponent<Props> = ({ navigation }) => {
  // ... your component
}

MyScreen.navigationOptions = {
  // ... your navigation options
}

export default MyScreen

对于 react-navigation v4,你有 react-navigation-tabsreact-navigation-stack 作为单独的库,你需要做一些类似于 的事情,但你只需要使用来自正确库的正确类型。例如,如果是来自createStackNavigator的屏幕,则需要执行:

import {
  NavigationStackScreenComponent,
  NavigationStackScreenProps
} from 'react-navigation-stack'

interface Props extends NavigationStackScreenProps {
  // your props...
}

export const HomeScreen: NavigationStackScreenComponent<Props> = ({ navigation }) => {
  return (
    <View>
      <Text>Home</Text>
    </View>
  )
}

HomeScreen.navigationOptions = {
  // your options...
}

同样,react-navigation-tabs 库具有 NavigationBottomTabScreenComponentNavigationTabScreenProps 等类型,您可以使用这些类型。