我正在尝试使用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>
)
}
}
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
属性?
答案 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);
的测试
答案 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);