了解React高阶组件(HOC)和打字稿

时间:2018-06-05 15:01:47

标签: reactjs typescript higher-order-components

简短版

为什么我必须导入我不在由打字稿中的高阶组件包装的文件中使用的类型?

长版

在打字稿中创建Higher Order Component(短HOC)时,我会发现以下两种打字稿错误:

TS4082

ERROR in ./A.tsx
error TS4082: Default export of the module has or is using private name 'BProps'.
ERROR in ./B.tsx
error TS4082: Default export of the module has or is using private name 'AProps'.

TS2345

error TS2345: Argument of type '...' is not assignable to parameter of type 'Attributes & Props'.
Object literal may only specify known properties, and 'foo' does not exist in type 'Attributes & Props'.

This question详细介绍如何与HOC合作,但没有帮助我解决为什么

为什么在此示例中我需要使用注释// WHY?标记的导入? (如果我删除其中任何一个,我会收到打字稿错误):

myHoc.tsx

import { AProps } from './A';
import { BProps } from './B';
...

export interface Props { ... }
export interface State { ... }
export interface myHocProps { ... }

export default (Component: React.ComponentType) => {
    return class extends React.Component<Props & AProps & BProps, State> {
        ...
    }
}

A.tsx

import { BProps } from './B';  // WHY?
import withSearch, {
    Props,  // WHY?
    State,  // WHY?
    myHocProps } from './myHoc';
...

export interface AProps { ... }

export class A extends React.Component<AProps & myHocProps> {
    ...
}

export default myHoc(A);

B.tsx

import { AProps } from './A';  // WHY?
import withSearch, {
    Props,  // WHY?
    State,  // WHY?
    myHocProps } from './myHoc';
...

export interface BProps { ... }

export class  extends React.Component<BProps & myHocProps> {
    ...
}

export default myHoc(B);

0 个答案:

没有答案
相关问题