How to set navigationOptions on stateless component with Typescript

后端 未结 4 1259
有刺的猬
有刺的猬 2020-12-16 13:18

I have a react component like

const Example = () => (...);

Using react-navigation I would normally apply naviga

相关标签:
4条回答
  • 2020-12-16 13:27

    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.

    0 讨论(0)
  • 2020-12-16 13:40

    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.

    0 讨论(0)
  • 2020-12-16 13:41

    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
    
    
    0 讨论(0)
  • 2020-12-16 13:44

    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 = {
            /*
            ...
            */
        }
    
    0 讨论(0)
提交回复
热议问题