【发布时间】:2020-08-21 23:42:18
【问题描述】:
我,试图创建一个模拟原生 html 元素的反应组件。
问题一:
允许有效的 html 属性
例子:
type TAtt = {
[key: string]: React.HTMLAttributes<HTMLElement>;
};
const NavAnyValidAttribute: React.FC<TAtt> = props => {
const { children, ...therest } = props;
return <nav {...therest}>{children}</nav>;
};
<NavAnyValidAttribute className="x">some children</NavAnyValidAttribute>;
错误
“字符串”类型与“HTMLAttributes”类型没有共同的属性。(2559) input.tsx(135, 3):预期的类型来自这个索引签名。
问题2:
type TProps = TAtt & {
TagName: string; //keyof JSX.IntrinsicElements - also doesn't work!;
}
const Tag: React.FC<TProps> = ({ TagName, children, ...props }) =>
React.createElement(TagName, props, children);
const Nav = <Tag {...{ TagName: 'nav' }} />;
错误:类型 '{ TagName: string; }' 不可分配给类型 'TAtt'。 属性“TagName”与索引签名不兼容。 “string”类型与“HTMLAttributes”类型没有共同的属性。ts(2322)
任何帮助表示赞赏。 谢谢
【问题讨论】:
-
“我正在尝试创建一个模拟原生 HTML 元素的 React 组件。” - 为什么?
-
所以我可以将它传递给这个方法:stackoverflow.com/questions/63482262/…
标签: reactjs typescript