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

时间:2018-03-05 18:29:57

标签: reactjs typescript react-native react-navigation

我有一个反应组件,如

const Example = () => (<View>...</View>);

使用反应导航我通常会通过说

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

使用打字稿我收到错误

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

我该如何解决这个问题?

我尝试编写一个界面

interface ExampleWithNavigationOptions extends Element {
    navigationOptions?;
}

但没有运气。

4 个答案:

答案 0 :(得分:12)

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

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

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

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

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

答案 1 :(得分:3)

您可以使用以下内容:

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

答案 2 :(得分:3)

对于react-navigation v4,将react-navigation-tabsreact-navigation-stack作为单独的库,您需要执行与Sat Mandir Khalsa's answer类似的操作,但是您只需要使用正确的类型来自正确的库。例如,如果它是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之类的类型,您可以代替使用。

答案 3 :(得分:1)

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