如何在打字稿中使用react-navigation的withNavigation?

时间:2018-07-30 01:16:04

标签: reactjs typescript react-native react-navigation

我正在尝试使用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>
    )
  }
}

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认为我应该手动为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 个答案:

答案 0 :(得分:4)

您只是缺少Partial <>接口,该接口包装了Navigation {InjectedProps},此问题已在此pull request中进行了描述。

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

的测试

答案 1 :(得分:1)

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