如何在typescript中使用react导航的 withNavigation?

IT技术 reactjs typescript react-native react-navigation
2021-05-07 04:54:11

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

主屏幕

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

转到配置按钮

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 认为我应该手动提供navigation属性GoToConfigButton

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

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

2个回答

您只是缺少 Partial<> 接口来包装您的 NavigationInjectedProps,因为它在此问题已修复的拉取请求有所描述

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 测试

import styles from "./styles";

import React, { PureComponent } from "react";

import { Button } from "react-native-elements";
import {
  DrawerItems,
  NavigationInjectedProps,
  SafeAreaView,
  withNavigation
} from "react-navigation";

class BurgerMenu extends PureComponent<NavigationInjectedProps> {
  render() {
    return (
      <SafeAreaView style={styles.container} >

        <Button
          icon={{ name: "md-log-out", type: "ionicon" }}
          title={loginStrings.logOut}
          iconContainerStyle={styles.icon}
          buttonStyle={styles.button}
          titleStyle={styles.title}
          onPress={() => this.props.navigation.navigate("LoginScreen")}
        />
      </SafeAreaView>
    );
  }
}

export default withNavigation(BurgerMenu);