【问题标题】:React-Native Navigation with typescript使用 typescript 的 React-Native 导航
【发布时间】:2019-09-16 10:10:27
【问题描述】:

我试图用 Typescript 实现 react native。在尝试访问 react-navigation library 时。它抛出打字稿错误。

类型'Readonly & Readonly'。

我的组件.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>
    )

}

}

导出默认首页;

请告诉我如何解决此错误。另外请指点我使用接口实现类型。

【问题讨论】:

    标签: reactjs typescript react-native


    【解决方案1】:

    我认为这个错误是由于 TypeScript 的严格模式和你的道具上没有类型,因为它不会在严格模式下编译没有类型的道具,因此你的错误。这是因为您创建了一个带有全新构造函数的新类,而 TypeScript 不知道需要哪些参数。

    我不熟悉 TS 和 react,但是你可以试试这样的:

    interface IPropType { 
      // props goes here
      // title: string;
      // quantity: number;
    }
    
    class FirstPage extends Component<IPropType> {
    
    constructor(props: IPropType) {
        super(props);
    }
    

    你也可以从模型文件中导入类型/接口,没关系。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-14
      • 1970-01-01
      • 1970-01-01
      • 2020-12-26
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      相关资源
      最近更新 更多