简体   繁体   English

带打字稿的React-Native导航

[英]React-Native Navigation with typescript

I was trying to implement react native with Typescript. 我试图用Typescript实现本机反应。 while trying to access react-navigation library . 尝试访问react-navigation库时。 Its throwing typescript errors. 其引发打字稿错误。

Property 'navigation' does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; 属性'navigation'在类型'Readonly <{}>和Readonly <{children?上不存在:ReactNode; }>'. }>'。

My component.tsx 我的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>
    )

}

} }

export default FirstPage; 导出默认的FirstPage;

Please let me know how to resolve this errors. 请让我知道如何解决此错误。 In addition please point me towards implementing types using interfaces. 另外,请指出要使用接口实现类型。

I think this error is due to TypeScript's strict mode and no types on your props, as it won't compile props without types in strict mode hence your error. 我认为此错误是由于TypeScript的严格模式导致的,并且道具上没有类型,因为如果没有严格模式下的类型,它将无法编译道具,因此会出现错误。 This is because you create a new class, with a completely new constructor, and TypeScript does not know which parameters to expect. 这是因为您创建了一个具有全新构造函数的新类,而TypeScript不知道期望使用哪些参数。

I'm not familiar with TS and react, but you can try something like this: 我不熟悉TS并做出反应,但是您可以尝试执行以下操作:

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

class FirstPage extends Component<IPropType> {

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

You can also import the type(s)/interfaces from a model file, it does't matter. 您也可以从模型文件中导入类型/接口,这无关紧要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM