如何在打字稿中使用 react-navigation 的 withNavigation?
Posted
技术标签:
【中文标题】如何在打字稿中使用 react-navigation 的 withNavigation?【英文标题】:How to use react-navigation's withNavigation in typescript? 【发布时间】:2019-01-06 05:27:27 【问题描述】:我正在尝试将 react-native、react-navigation 和 typescript 一起使用来创建一个应用程序。总共只有两个屏幕(HomeScreen
和ConfigScreen
)和一个组件(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
自动提供的?
【问题讨论】:
看起来 withNavigation 函数应该去掉 NavigationInjectedProps 接口。 github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/… 没关系,但是您可以尝试将 class GoToConfigButton extends React.ComponentReact.Component<NavigationInjectedProps>
和 React.Component< & NavigationInjectedProps>
有什么区别
【参考方案1】:
您只是缺少包装 NavigationInjectedProps 的 Partial 接口,正如此问题已修复的 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测试
【讨论】:
这不起作用。我无法将组件传递给此函数。【参考方案2】: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);
【讨论】:
以上是关于如何在打字稿中使用 react-navigation 的 withNavigation?的主要内容,如果未能解决你的问题,请参考以下文章
如何在打字稿中使用 singleton() 在构造函数中传递值?