typescript 为反应导航道具添加强类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47924501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:08:04  来源:igfitidea点击:

Add strong typing for react navigation props

typescriptreact-nativereact-navigation

提问by Mellet

I'm using typescript in my react-native project(expo).

我在我的本机项目(博览会)中使用打字稿。

The project uses react-navigation, so on my screens I can set navigationOptionsand I have access to the prop navigation.

该项目使用 react-navigation,所以在我的屏幕上我可以设置navigationOptions并且我可以访问 prop navigation

Now I'm trying to strongly type these so I get hints for what properties are available to set.

现在我正在尝试强输入这些,以便我获得有关可以设置哪些属性的提示。

interface NavStateParams {
    someValue: string
}

interface Props extends NavigationScreenProps<NavStateParams> {
   color: string
}

class Screen extends React.Component<Props, any> {
    // This works fine
    static navigationOptions: NavigationStackScreenOptions = {
        title: 'ScreenTitle'
    }
    // Does not work
    static navigationOptions: NavigationStackScreenOptions = ({navigation, screenProps }) => ({
        title: navigation.state.params.someValue
    })
}

What would be the best way to handle react-navigation as props for components.

将反应导航作为组件的道具处理的最佳方法是什么。

回答by Andrej Kyselica

Just add NavigationType to your Props, like this:

只需将 NavigationType 添加到您的道具中,如下所示:

    import { StackNavigator, NavigationScreenProp } from 'react-navigation';

    export interface HomeScreenProps {
      navigation: NavigationScreenProp<any,any>
    };

    export class HomeScreen extends React.Component<HomeScreenProps, object> {

      render() {
        return (
          <View style={styles.container}>       
            <Button
              title="Go to Details"
              onPress={() => this.props.navigation.navigate('Details')}
            />
          </View>
        );
      }
    }

回答by Adiono

I have same issue, and here's my solution:

我有同样的问题,这是我的解决方案:

import * as React from 'react'
import { NavigationScreenProps, NavigationStackScreenOptions } from 'react-navigation'

interface NavStateParams {
  someValue: string
}

// tslint:disable-next-line:no-any
type NavigationOptionsFn<TParams=any> = (props: NavigationScreenProps<TParams>) => NavigationStackScreenOptions

class Screen extends React.Component {
  // This should works fine
  static navigationOptions: NavigationOptionsFn<NavStateParams> = ({ navigation, screenProps }) => ({
    title: navigation.state.params.someValue
  })
}

You may want to declare NavigationOptionsFn<TParams>type into some d.tsfile to make it work globally.

您可能希望在NavigationOptionsFn<TParams>某个d.ts文件中声明类型以使其在全局范围内工作。

回答by J. Hesters

This works:

这有效:

static navigationOptions = ({ navigation }: NavigationScreenProps) => ({
  ...
})

回答by Javier González

 yarn add --dev @types/jest @types/react-navigation

import { NavigationScreenProps } from "react-navigation";

export interface ISignInProps extends NavigationScreenProps<{}> { userStore: IUserStore }

export class SignInScreen extends React.Component { .... }

回答by Iwaz

public static navigationOptions: NavigationScreenConfig<NavigationStackScreenOptions> = 
    ({navigation}) => ({/* Your options... */})

回答by Skyler

In case anyone is still experiencing this issue while extending NavigationScreenPropsso you can correctly type navigationOptionsetc along with your own props:

如果有人在扩展时仍然遇到此问题,NavigationScreenProps以便您可以正确键入navigationOptions等以及您自己的道具:

interface Props extends NavigationScreenProps {
  someProp: string;
  anotherProp: string;
}

export const SomeGreatScreen: NavigationScreenComponent<NavigationParams, {}, Props> = ({
  someProp,
  anotherProp,
}) => {
...
};

Whereas NavigationScreenComponent<Props>resulted in type errors for the destructured properties { someProp, anotherProp }, not recognizing the extension to the props, NavigationScreenComponent<NavigationParams, {}, Props>did. This appears to be due to the need to send the extended props type as the third parameter:

NavigationScreenComponent<Props>导致解构属性的类型错误{ someProp, anotherProp },无法识别道具的扩展,NavigationScreenComponent<NavigationParams, {}, Props>确实如此。这似乎是由于需要将扩展​​的 props 类型作为第三个参数发送:

  export type NavigationScreenComponent<
    Params = NavigationParams,
    Options = {},
    Props = {}
  > = React.ComponentType<NavigationScreenProps<Params, Options> & Props> & {
    navigationOptions?: NavigationScreenConfig<Options>;
  };

from react-navigation.d.ts

react-navigation.d.ts

回答by Kruup?s

Rather than describing manually all your navigation functions(e.g: navigate), in your Props' interface, you can directly extends NavigationScreenProps.

无需手动描述所有导航功能(例如:导航),在您的 Props 界面中,您可以直接扩展NavigationScreenProps.

In my case it was mandatory to stop eslint from yielding an error.

就我而言,必须阻止 eslint 产生错误。

import { StackNavigator, NavigationScreenProps } from 'react-navigation';

export interface HomeScreenProps extends NavigationScreenProps {
/* your custom props here */
};

export class HomeScreen extends React.Component<HomeScreenProps, object> {

  render() {
    return (
      <View style={styles.container}>       
        <Button
          title="Go to Details"
          onPress={() => this.props.navigation.navigate('Details')}
        />
      </View>
    );
  }
}

回答by Vladyslav Zavalykhatko

The does not worksection contains an error if your tsconfig.jsonhas "strictNullChecks": true. In this case, you have an error indeed, because in the line

does not work部分包含一个错误,如果你tsconfig.json"strictNullChecks": true。在这种情况下,您确实有错误,因为在该行中

navigation.state.params.someValue

navigation.state.params.someValue

paramsis optional. What you could do is to check if the value was passed inside and provide default one otherwise, like:

params是可选的。您可以做的是检查该值是否在内部传递,否则提供默认值,例如:

title: navigation.state.params && navigation.state.params.someValue || 'Default title'

title: navigation.state.params && navigation.state.params.someValue || 'Default title'

回答by Simon Reggiani

This seems to work:

这似乎有效:

public static navigationOptions: NavigationScreenOptionsGetter<
  NavigationScreenOptions
> = (navigation, stateProps) => ({
  title: navigation.state.params.someValue,
});

回答by Abhisek Padhi

I think with react-navigation5.X it's simpler now. Here is how to type hint navigationprops passed to screens/components:

我认为react-navigation5.X 现在更简单了。以下是如何键入navigation传递给屏幕/组件的提示道具:

export default class Header extends React.Component<{
    navigation: StackNavigationHelpers;
}> {
...
}

Ps: Tested with these versions

Ps:用这些版本测试过

"@react-navigation/native": "^5.2.3",
"@react-navigation/stack": "^5.3.1",