【问题标题】:Typescript: Type representing a generic React component or HTML element, and its propsTypescript:表示通用 React 组件或 HTML 元素的类型,及其道具
【发布时间】:2021-09-04 08:06:01
【问题描述】:

我正在编写一个快速包装界面。我正在寻找一些神秘类型:

Foo 成为一些 React 组件,接受 FooProps 类型的 props。

X 成为代表任何通用 React 组件或任何 HTML 元素的接口。哪里有Foo extends X,还有div extends XX 是可以被<X></X> 转换成 JSX.Element 的任何东西

Y<T extends X> 成为我们T 的道具,这又是任何元素,例如Foodiv。其中Y<Foo> = FooPropsY<div> = { className: string, ... }

我们可以这样写:

interface WrapperProps<T extends X>{
    children?: React.ReactNode;
    attributes?: Y<T>;
}

那么我们可以这样写:

const props: WrapperProps<T> = ...;
const el: JSX.Element = (
    <T {...attributes}>
        { children }
    </T>
);

XY这些神秘类型是什么?

【问题讨论】:

    标签: reactjs typescript jsx


    【解决方案1】:

    我相信您正在寻找的是:

    type WrapperProps<T extends keyof JSX.IntrinsicElements | React.JSXElementConstructor<any>> = {
        children?: React.ReactNode;
        attributes: Omit<React.ComponentProps<T>, 'children'>;
    }
    

    playground link

    注意必需的attributes 属性。虽然您可以将任何属性设为可选,但您根本不能省略它们。

    这里使用的反应类型:

    JSX.IntrinsicElements(太大,此处无法包含)。

    JSXElementConstructor:

    type JSXElementConstructor<P> =
        | ((props: P) => ReactElement<any, any> | null)
        | (new (props: P) => Component<P, any>);
    

    ReactComponentProps:

    type ComponentProps<T extends keyof JSX.IntrinsicElements | JSXElementConstructor<any>> =
        T extends JSXElementConstructor<infer P>
            ? P
            : T extends keyof JSX.IntrinsicElements
                ? JSX.IntrinsicElements[T]
                : {};
    

    【讨论】:

      猜你喜欢
      • 2019-07-27
      • 2021-05-11
      • 2018-08-08
      • 2021-01-24
      • 2022-12-11
      • 2019-12-16
      • 1970-01-01
      • 2017-11-28
      • 2021-11-23
      相关资源
      最近更新 更多