How to use react-navigation's withNavigation i

2019-05-14 23:13发布

问题:

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.

HomeScreen

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

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>

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

回答1:

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

Tested with @types/react-navigation >= 2.13.0