为反应导航道具添加强类型 [英] Add strong typing for react navigation props

查看:50
本文介绍了为反应导航道具添加强类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 react-native 项目 (expo) 中使用了 typescript.

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

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

The project uses react-navigation, so on my screens I can set navigationOptions and I have access to the 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.

推荐答案

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

Just add NavigationType to your Props, like this:

    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>
        );
      }
    }

这篇关于为反应导航道具添加强类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆