如何在打字稿中使用反应导航的 withNavigation? [英] How to use react-navigation's withNavigation in typescript?

查看:29
本文介绍了如何在打字稿中使用反应导航的 withNavigation?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 react-native、react-navigation 和 typescript 结合使用来创建应用程序.总共只有两个屏幕(HomeScreenConfigScreen)和一个组件(GoToConfigButton),如下所示.

I'm trying to use react-native, react-navigation and typescript together to create an app. There are only two screens(HomeScreen and ConfigScreen) and one component(GoToConfigButton) in total, as follows.

import React from "react";
import { NavigationScreenProps } from "react-navigation";
import { Text, View } from "react-native";
import GoToConfigButton from "./GoToConfigButton";

export class HomeScreen extends React.Component<NavigationScreenProps> {
  render() {
    return (
      <View>
        <Text>Click the following button to go to the config tab.</Text>
        <GoToConfigButton/>
      </View>
    )
  }
}

GoToConfigButton

import React from "react";
import { Button } from "react-native";
import { NavigationInjectedProps, withNavigation } from "react-navigation";

class GoToConfigButton extends React.Component<NavigationInjectedProps> {
  render() {
    return <Button onPress={this.handlePress} title="Go" />;
  }
  private handlePress = () => {
    this.props.navigation.navigate("Config");
  };
}
export default withNavigation(GoToConfigButton);

ConfigScreen 的代码没有给出,因为它在这里并不重要.好吧,实际上上面的代码有效,我可以通过单击按钮进入配置屏幕.问题是,Typescript 认为我应该手动为 GoToConfigButton 提供 navigation 属性.

The code for ConfigScreen is not given because it's not important here. Well, actually the above code works, I can go to the config screen by clicking on the button. The problem is, Typescript thinks I should provide the navigation property to GoToConfigButton manually.

<View>
  <Text>Click the following button to go to the config tab.</Text>
  <GoToConfigButton/>  <-- Property "navigation" is missing.
</View>

如何告诉 Typescript navigation 属性是由 react-navigation 自动给出的?

How can I tell Typescript that the navigation property is given automatically by react-navigation?

推荐答案

您只是缺少 Partial<> 接口包装您的 NavigationInjectedProps,如本 pull request 已修复此问题.

You were just missing Partial<> interface wrapping your NavigationInjectedProps as it is described in this pull request where this issue was fixed.

import React from "react";
import { Button } from "react-native";
import { NavigationInjectedProps, withNavigation } from "react-navigation";

class GoToConfigButton extends React.Component<Partial<NavigationInjectedProps>> {
    render() {
        return <Button onPress={this.handlePress} title="Go" />;
    }

    private handlePress = () => {
        this.props.navigation.navigate("Config");
    };
}

export default withNavigation(GoToConfigButton);

使用 @types/react-navigation >= 2.13.0

这篇关于如何在打字稿中使用反应导航的 withNavigation?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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