类组件继承

来源:7-1 导航器基本介绍

Forest211

2021-07-19

老师,我看课程中基本上的页面都会有个navigaton和route两个属性,我想把它提成一个公共类,然后其他的子类继承这个公共类;但是在实现过程中遇到state和props的数据不能共享的问题

import React, { Component } from 'react';
import { View } from 'react-native';

interface Props {}

interface State {
    name: boolean;
}

export default class Base<P, S> extends Component<Props & P, State & S> {
    constructor(props: Props) {
        super(props)
        this.state = {
            name: false,
        };
    }
}

图片描述
图片描述
在子类继承时,也会出错

import React, { Component } from 'react';
import { Text, View } from 'react-native';
import Base from './Base';

interface Props {}
interface State {
    loading: boolean;
}
export default class App extends Base<Props, State> {
    constructor(props: Props) {
        super(props)
        this.state = {
            loading: false
        }
    } 
    render() {
        console.log(this.state);
        console.log(super.state);
        return (
            <View>
                <Text
                    style={{
                        color: 'red',
                        fontSize: 22,
                        marginTop: 30,
                        marginLeft: 20,
                    }}>
                    app
                </Text>
            </View>
        );
    }
}

图片描述

劳烦老师解惑!谢谢

写回答

1回答

今朝

2021-07-27

不用你自己写的,使用函数组件,可以使用对应的hook函数获取

0
1
Forest211
老师,能否具体点呢
2021-07-27
共1条回复

跨平台应用ReactNative+TypeScript仿喜马拉雅开发App

从入门到实战,掌握用TypeScript开发ReactNative应用

842 学习 · 341 问题

查看课程