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

问题描述 投票:8回答:3

我有一个反应组件

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

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

Example.navigationOptions = { options };

使用打字稿我得到错误

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

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

我试着写一个界面

interface ExampleWithNavigationOptions extends Element {
    navigationOptions?;
}

但没有运气。

reactjs typescript react-native react-navigation
3个回答
16
投票

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

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

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

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

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

14
投票

您可以使用以下内容:

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
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.