React/TypeScript:使用附加属性扩展组件

新手上路,请多包涵

我正在尝试使用 react 来重新创建我的当前组件(用纯打字稿编写),但我找不到一种方法来为扩展另一个组件的组件提供额外的道具。

 export interface DataTableProps {
    columns: any[];
    data: any[];
}

export class DataTable extends React.Component<DataTableProps, {}> {
   render() {
       // -- I can use this.props.columns and this.props.data --
   }
}

export class AnimalTable extends DataTable {
    render() {
       // -- I would need to use a this.props.onClickFunction --
    }
}

我的问题是我需要给 AnimalTable 一些与 DataTable 无关的道具。我怎样才能做到这一点 ?

原文由 Emarco 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 839
2 个回答

您需要使 DataTable 通用,以便您能够使用扩展 DataTableProps 的接口:

 export interface AnimalTableProps extends DataTableProps {
    onClickFunction: Function;
}

export class DataTable<T extends DataTableProps> extends React.Component<T, {}> { }

export class AnimalTable extends DataTable<AnimalTableProps> {
    render() {
        // this.props.onClickFunction should be available
    }
}

原文由 Nitzan Tomer 发布,翻译遵循 CC BY-SA 3.0 许可协议

根据经验,最好避免继承。幸运的是 TS 和 React 是允许这样做的好工具(不像 c#,例如,继承通常会为你节省一堆样板文件)

 export interface DataTableProps {
    columns: any[];
    data: any[];
}

export class DataTable extends React.Component<DataTableProps, {}> {
   render() {
       // -- I can use this.props.columns and this.props.data --
   }
}

export type AnimalTableProps = DataTableProps & {
    onClickFunction: () => void;
};

export class AnimalTable extends React.Component<AnimalTableProps, {}> {
    render() {
        const {onClickFunction, ...tableProps} = this.props;
        // use onClickFunction however you need it
        return <DataTable {...tableProps}></DataTable>
    }
}

原文由 ironic 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进