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

xer*_*ant 13 typescript reactjs react-native react-navigation

我有一个反应组件

const Example = () => (<View>...</View>);
Run Code Online (Sandbox Code Playgroud)

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

Example.navigationOptions = { options };
Run Code Online (Sandbox Code Playgroud)

使用打字稿我得到错误

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

我怎样才能解决这个问题?

我试着写一个界面

interface ExampleWithNavigationOptions extends Element {
    navigationOptions?;
}
Run Code Online (Sandbox Code Playgroud)

但没有运气.

Sat*_*lsa 22

您可以使用以下内容:

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

Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案。公认的是与TypeScript对抗的fight弱的技巧,但不接受它的甜美。 (3认同)
  • “NavigationScreenProps”似乎不再存在。这对我有用: `NavigationScreenComponent&lt; OwnProps, NavigationBottomTabScreenComponent &gt;` (3认同)

Bob*_*Bob 16

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

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

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

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

    Example.propTypes = {
        /*
        ...
        */
    }
Run Code Online (Sandbox Code Playgroud)

  • 将 navigationOptions 定义为对象的要点是什么...类型的要点是要知道这是为了什么 (3认同)

saa*_*adq 9

对于react-navigationv4,您拥有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...
}
Run Code Online (Sandbox Code Playgroud)

同样,react-navigation-tabs图书馆类型,如NavigationBottomTabScreenComponentNavigationTabScreenProps,您可以使用来代替。