【问题标题】:How to declare React.Component type for sub-components?如何为子组件声明 React.Component 类型?
【发布时间】:2021-04-25 16:48:12
【问题描述】:

我使用带有 React 组件的外部库(例如“ui”):

import { Input } from 'ui'

export const LoginForm = () => (
    <Input name="login" value={login} />
    <Input.Password name="password" value={password} />
)

我有一些类型声明 (types/ui.d.ts):

declare namespace Ui {
    export interface InputProps {
        value?: string;

    }
    export class Input extends React.Component<InputProps> {
        static Password: any;
    }
}

declare module 'ui' {
    export import Input = Ui.Input;
}

如何声明Input.Password的类型?

我尝试了什么:

export class InputPassword extends React.Component<InputPasswordProps> {
   // ... 
}
declare namespace Ui {
    export interface InputProps {
        value?: string;

    }
    export class Input extends React.Component<InputProps> {
        static Password: InputPassword;
    }
}

但我收到错误:

JSX element type 'Input.Password' does not have any construct or call signatures.ts(2604)

【问题讨论】:

  • 我几天前回答的问题基本相同:stackoverflow.com/a/65783246/10431574 需要一些as 转换才能将一个组件作为另一个组件的属性,但这是可行的。
  • 我没有足够的信心将其发布为答案,但如果可行,请告诉我:tsplay.dev/OwEZ3N
  • @LindaPaiste 它对我不起作用。我的代码有什么不同?
  • 不同之处在于您尝试使用外部库覆盖/合并声明,而不是为自己的组件声明类型。实际的包装是什么?
  • 我使用来自私有公司 npm 存储库(不是来自 npmjs.com)的 ui-library。此 ui 库包含组件 Input 和子组件 Input.Password

标签: reactjs typescript typescript-typings react-typescript


【解决方案1】:

它对我有用:

declare namespace SbolLibUi {
    interface InputPasswordProps extends InputPropsBase {
        // specific properties
    }
    interface InputProps extends InputPropsBase {
        // specific properties
    }

    declare class Input extends React.Component<InputProps> {
        static readonly Password = class extends React.Component<InputPasswordProps> {
            // specific properties
        };
    }

    declare module 'ui' {
        export import Input = Ui.Input;
    }
}

【讨论】:

    猜你喜欢
    • 2018-09-14
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 2018-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多