首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React Native -导航中的屏幕间移动错误

React Native -导航中的屏幕间移动错误
EN

Stack Overflow用户
提问于 2018-08-27 16:51:39
回答 4查看 1.7K关注 0票数 2

我正在学习在屏幕之间移动的教程。我找到了HomeScreen.js文件,在那里我得到了导航的红色错误。当我在导航上悬停时,我得到了错误

代码语言:javascript
复制
[ts] Property 'navigation' does not exist on type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'.
any

当我在“反应导航”上徘徊时,我会得到

代码语言:javascript
复制
"[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';`"

这是我的代码

代码语言:javascript
复制
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;
EN

回答 4

Stack Overflow用户

发布于 2018-08-27 16:55:16

正如第二条错误消息所说的,您需要为react导航包安装typescript定义模块。你可以用npm install --save-dev @types/react-navigation做到这一点。

另外,对于第一个错误,请确保您实际上用createStackNavigator包装了组件。这将使您能够访问导航道具。

代码语言:javascript
复制
export default createStackNavigator({
  Home: {
    screen: HomeScreen
  },
});

因为你使用的是typescript,所以你需要声明状态和属性的接口。你应该用react查看typescript,它看起来像这样:

class HomeScreen extends React.Component<PropsInterface, StateInterfaces>,其中PropsInterface类似于:

export interface HelloProps { navigation: <Type_From_Definition>; }

票数 3
EN

Stack Overflow用户

发布于 2018-08-27 17:12:53

此错误:

代码语言:javascript
复制
   Could not find a declaration file for module 'react-navigation'.
   Try `npm install @types/react-navigation

说你要安装react-导航模块。

因此,只需通过在项目文件夹中运行以下命令来安装它:

代码语言:javascript
复制
npm install react-navigation

代码语言:javascript
复制
npm install @types/react-navigation
票数 1
EN

Stack Overflow用户

发布于 2018-08-27 17:07:46

这不是问题的解决方案,但在改进方面,我建议您检查this.props.navigation是否未定义,因为您直接访问this.props.navigation.navigate,所以如果在this.props.navigation未定义的情况下直接执行此操作,则会产生问题

为了安全起见,添加如下条件检查

代码语言:javascript
复制
 {this.props.navigation && this.props.navigation != undefined && <Button title="Go to Details" onPress={() => this.props.navigation.navigate('Details')} />}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52035694

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档