React/TypeScript: extending a component with additional properties

前端 未结 5 604
梦如初夏
梦如初夏 2021-02-01 16:05

I am trying to use react to recreate my currents components (written in pure typescript) but I can\'t find a way to give additional props to a component extending an other.

5条回答
  •  滥情空心
    2021-02-01 16:33

    as a rule of thumb it is probably better to avoid inheritance. luckily TS and react are great tools allowing that (unlike c# for example, where inheritance often saves you a bunch of boilerplate)

    export interface DataTableProps {
        columns: any[];
        data: any[];
    }
    
    export class DataTable extends React.Component {
       render() {
           // -- I can use this.props.columns and this.props.data --
       }
    }
    
    export type AnimalTableProps = DataTableProps & {
        onClickFunction: () => void;
    };
    
    export class AnimalTable extends React.Component {
        render() {
            const {onClickFunction, ...tableProps} = this.props;
            // use onClickFunction however you need it
            return 
        }
    }
    

提交回复
热议问题