【发布时间】: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.Component
{ 更改为 class GoToConfigButton extends React.Component { -
@AndrejKyselica 有效!但如何?为什么?
React.Component<NavigationInjectedProps>和React.Component<{} & NavigationInjectedProps>有什么区别
标签: reactjs typescript react-native react-navigation