我有一个新的 react native 应用程序,使用打字.我想使用基于类的组件.此时,我有两节课:

RouteView.tsx

 export class RouteView extends React.Component {
    constructor(props: any, private title: string) {
        super(props);

        this.params = params;
        this.title = title;    
    }

    render() {
        return <div></div>;
    }
 }

HomeView.tsx

export class HomeView extends RouteView {
  render() { return 
    <View style={styles.container}>
      <Text>My Mobile App!</Text>
      <StatusBar style="auto" />
      <Button
        title="View About"
        onPress={() => navigation.navigate('About')}
      />
    </View>;
  }
}

const styles = StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: '#fff',
      alignItems: 'center',
      justifyContent: 'center',
    },
  });

当我编译这段代码时,我收到一条错误消息:

Property 'render' in type 'HomeView' is not assignable to the same property in base type 'RouteView'.

为什么?代码在我看来是正确的.在HomeView中,我try 覆盖基类的render方法.我做错了什么?

推荐答案

101 don't do inheritance.为什么继承是解决问题的错误方式,以及为什么组合解决了从最小规模到最大规模的应用程序的所有问题,这方面的react 有很长的历史.

立即回答

给出您的snack,看起来您的RETURN语句正在返回JSX.它应该如下所示:

export class HomeView extends RouteView {
  render() { 
    return (
     <View style={styles.container}>
       <Text>My Mobile App!</Text>
       <StatusBar style="auto" />
       <Button
         title="View About"
         onPress={() => navigation.navigate('About')}
       />
     </View>
    )
  }
}

enter image description here

Typescript相关问答推荐

如何根据参数的值缩小函数内的签名范围?

调用另一个函数的函数的Typescript类型,参数相同

如何从TypScript中的接口中正确获取特定键类型的所有属性?

如何将联合文字类型限制为文字类型之一

迁移到Reaction路由V6时,获取模块Reaction-Router-Dom';没有导出的成员RouteComponentProps错误

类型脚本`Return;`vs`Return unfined;`

当方法参数和返回类型不相互扩展时如何从类型脚本中的子类推断类型

PrimeNG日历需要找到覆盖默认Enter键行为的方法

如果数组使用Reaction-Hook-Form更改,则重新呈现表单

使用动态输出类型和泛型可重用接口提取对象属性

刷新页面时,TypeScrip Redux丢失状态

为什么特定的字符串不符合包括该字符串的枚举?

接口中可选嵌套属性的类型判断

推断集合访问器类型

如何在Reaction Native中关注屏幕时正确更新状态变量?

更漂亮的格式数组<;T>;到T[]

Typescript泛型调用对象';s方法

使用NextJS中间件重定向,特定页面除外

TS2532:对象可能未定义

如果父级被删除或删除,如何自动删除子级?