我正在学习在屏幕之间移动的教程。我找到了HomeScreen.js文件,在那里我得到了导航的红色错误。当我在导航上悬停时,我得到了错误
[ts] Property 'navigation' does not exist on type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'.
any当我在“反应导航”上徘徊时,我会得到
"[ts]
Could not find a declaration file for module 'react-navigation'. 'd:/react-workspace/stack-navigator/node_modules/react-navigation/src/react-navigation.js' implicitly has an 'any' type.
Try `npm install @types/react-navigation` if it exists or add a new declaration (.d.ts) file containing `declare module 'react-navigation';`"这是我的代码
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
Button
} from 'react-native';
import { createStackNavigator } from 'react-navigation';
class HomeScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button
title="Go to Details"
onPress={() => this.props.navigation.navigate('Details')}
/>
</View>
);
}
}
export default HomeScreen;发布于 2018-08-27 16:55:16
正如第二条错误消息所说的,您需要为react导航包安装typescript定义模块。你可以用npm install --save-dev @types/react-navigation做到这一点。
另外,对于第一个错误,请确保您实际上用createStackNavigator包装了组件。这将使您能够访问导航道具。
export default createStackNavigator({
Home: {
screen: HomeScreen
},
});因为你使用的是typescript,所以你需要声明状态和属性的接口。你应该用react查看typescript,它看起来像这样:
class HomeScreen extends React.Component<PropsInterface, StateInterfaces>,其中PropsInterface类似于:
export interface HelloProps { navigation: <Type_From_Definition>; }
发布于 2018-08-27 17:12:53
此错误:
Could not find a declaration file for module 'react-navigation'.
Try `npm install @types/react-navigation说你要安装react-导航模块。
因此,只需通过在项目文件夹中运行以下命令来安装它:
npm install react-navigation或
npm install @types/react-navigation发布于 2018-08-27 17:07:46
这不是问题的解决方案,但在改进方面,我建议您检查this.props.navigation是否未定义,因为您直接访问this.props.navigation.navigate,所以如果在this.props.navigation未定义的情况下直接执行此操作,则会产生问题
为了安全起见,添加如下条件检查
{this.props.navigation && this.props.navigation != undefined && <Button title="Go to Details" onPress={() => this.props.navigation.navigate('Details')} />}https://stackoverflow.com/questions/52035694
复制相似问题