从作为字符串传递的标签类型获取属性

问题描述 投票:0回答:1

如何从作为字符串传递的标签中获取属性列表(任何/类型?/)。

export const createElement = (Component: ElementType) => {
    return ({...props }: any /*Type?*/) => (
        <Component
            {...props}
        />
    );
};
const Some = () => {
    const Textarea = createElement("textarea");
    const Input = createElement("input");

    return (
        <>
            <Textarea placeholder={"123"} type={"color"}/> {/*type={"color"} must be error*/}
            <Input type={"color"} />
        </>
    )
}

我需要当我传递属性时它们与传递的标签相对应

typescript types attributes
1个回答
0
投票

这里的要点:

  • JSX.IntrinsicElements
    是一种特殊类型,它将 HTML 元素的名称映射到其属性类型
  • 显式调用
    React.createElement()
    ——或者任何等效的东西,如果你的目标不是React——是从其名称作为字符串而不是组件函数创建元素所必需的

因此,您的

createElement
可能看起来像这样:

import React from 'react';

export const createElement = <T extends keyof JSX.IntrinsicElements>(elementName: T) => {
    return (props: JSX.IntrinsicElements[T]) => React.createElement(elementName, props);
};
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.