如何解决类型“ Readonly <{}>上不存在的属性“导航”,

时间:2019-04-18 01:03:19

标签: typescript react-native react-navigation

我有以下两段代码:

CustomHeader.tsx

import { View, StyleSheet, Button } from 'react-native';
import { NavigationScreenProps } from 'react-navigation';
import Icon from 'react-native-vector-icons/Ionicons';


export  const CustomHeader = ({ navigation }: NavigationScreenProps) => (
    <View style={[styles.container]}>
      <Icon
        name="md-menu"
        size={32}
        color="black"
        style={{ marginLeft: 10 }}
        onPress={() => navigation.openDrawer()}
      />
    </View>
  );

  const styles = StyleSheet.create({
    container: {
      borderBottomWidth: 2,
      height: 70,
      paddingTop: 20,
    },
  });

DetailScreen.tsx

import React from 'react';
import { Text, View, Button, Alert } from 'react-native';
import { NavigationScreenProps } from "react-navigation";
import { CustomHeader } from '../components/Header';

export class ChangeAccountDetailScreen extends React.Component {
  render() {
    return (
      <View style={{ flex: 1 }}>
        <CustomHeader navigation={this.props.navigation} />
        <Text style={{ fontSize: 20 }}>Profile Screen</Text>
      </View>
    );
  }
}

在详细屏幕中,出现以下错误:

  

类型'Readonly <{}>和Readonly <{子代不存在属性“导航”:ReactNode; }>'。

我搜索了该问题,并且我了解到该问题有一个事实,就是我没有在CustomHeader中声明类型。但是我不知道如何解决这个问题。我对打字稿有点陌生。有人可以向我解释如何解决此类型的问题吗?

3 个答案:

答案 0 :(得分:5)

我可能是错的,但是您是否尝试过添加navigation类型?

import React from 'react';
import { Text, View, Button, Alert } from 'react-native';
import { NavigationScreenProps } from "react-navigation";
import { CustomHeader } from '../components/Header';

interface Props {
  navigation: any
}

export class ChangeAccountDetailScreen extends React.Component<Props> {
  render() {
    return (
      <View style={{ flex: 1 }}>
        <CustomHeader navigation={this.props.navigation} />
        <Text style={{ fontSize: 20 }}>Profile Screen</Text>
      </View>
    );
  }
}

答案 1 :(得分:0)

答案 2 :(得分:0)

这是另一个解决方案,其中我在接口定义中添加了更多细节

import React from 'react';
import { Text, View, Button, Alert } from 'react-native';
import {
  NavigationParams,
  NavigationScreenProp,
  NavigationState
} from 'react-navigation';
import { CustomHeader } from '../components/Header';

interface Props {
  navigation: NavigationScreenProp<NavigationState, NavigationParams>
}

export class ChangeAccountDetailScreen extends React.Component<Props> {
  render() {
    return (
      <View style={{ flex: 1 }}>
        <CustomHeader navigation={this.props.navigation} />
        <Text style={{ fontSize: 20 }}>Profile Screen</Text>
      </View>
    );
  }
}