How to set navigationOptions on stateless component with Typescript

我们两清 提交于 2019-12-30 04:04:12

问题


I have a react component like

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

Using react-navigation I would normally apply navigation options by saying

Example.navigationOptions = { options };

With typescript I am getting the error

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

How can I fix this?

I tried writing an interface

interface ExampleWithNavigationOptions extends Element {
    navigationOptions?;
}

But with no luck.


回答1:


The key idea is to specify correct type for Example constant. Probably, react-navigation already provides that type. But, you can also extend build-in React interface smth like this:

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

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

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

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



回答2:


You can use the following:

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




回答3:


For react-navigation v4, where you have react-navigation-tabs and react-navigation-stack as separate libraries, you need to do something similar to Sat Mandir Khalsa's answer, but you just need to use the correct types from the correct library. For example, if it is a screen from createStackNavigator, you need to do:

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...
}

Likewise, the react-navigation-tabs library has types like NavigationBottomTabScreenComponent and NavigationTabScreenProps that you can use instead.




回答4:


If the case is that you want the same navigation option for all your components, remember you can set the defaultNavigationOptions in the createStackNavigator. Here is the React Navigation API if you need an example.



来源:https://stackoverflow.com/questions/49117173/how-to-set-navigationoptions-on-stateless-component-with-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!