带打字稿的React-Native导航

时间:2019-09-16 10:10:27

标签: reactjs typescript react-native

我试图用Typescript实现本机反应。尝试访问react-navigation库时。其引发打字稿错误。

  

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

我的component.tsx

    import React, { Component } from "react";
import { View, Text, TouchableHighlight, Alert } from "react-native";
import {
  NavigationParams,
  NavigationScreenProp,
  NavigationState,
} from 'react-navigation';

class FirstPage extends Component {

  public static navigationOptions = {
    title: 'Test Screen',
  };

constructor(props: any) {
    super(props);
}



_call = (firstName:string,lastName:string) => {

    Alert.alert(
        'Title',
        `${firstName} ${lastName}`,
        [
          {text: 'Ask me later', onPress: () => console.log('Ask me later pressed')},
          {
            text: 'Cancel',
            onPress: () => console.log('Cancel Pressed'),
            style: 'cancel',
          },
          {text: 'OK', onPress: () => console.log('OK Pressed')},
        ],
        {cancelable: false},
      );
   // Alert( `$(firstname) $(lastName)`)
}


_nav=()=>
{
 this.props.navigation.navigate('second');
}

render() {

    return (
        <View>
            <Text>Hello First Page</Text>
            <TouchableHighlight onPress={()=>this._call('hello','user')} >
                <Text>Types Button</Text>
            </TouchableHighlight>
            <TouchableHighlight onPress={()=>this._nav} >
                <Text>Types Button</Text>
            </TouchableHighlight>
        </View>
    )

}

}

导出默认的FirstPage;

请让我知道如何解决此错误。另外,请指出要使用接口实现类型。

1 个答案:

答案 0 :(得分:0)

我认为此错误是由于TypeScript的严格模式和您的道具上没有类型而导致的,因为如果没有严格模式下的类型,它将无法编译道具,因此是您的错误。这是因为您创建了一个具有全新构造函数的新类,而TypeScript不知道期望使用哪些参数。

我不熟悉TS并做出反应,但是您可以尝试执行以下操作:

interface IPropType { 
  // props goes here
  // title: string;
  // quantity: number;
}

class FirstPage extends Component<IPropType> {

constructor(props: IPropType) {
    super(props);
}

您还可以从模型文件中导入类型/接口,这没关系。