This question already has an answer here:
How do I type this 'as' JSX attribute in TypeScript?
(1个答案)
去年关闭。
我正在创建一个看起来像这样的组件:
我想获取
(1个答案)
去年关闭。
我正在创建一个看起来像这样的组件:
<Button component='a' href='/'>
Link
</Button>
我想获取
component
Prop 的类型定义,因此我可以自动将其包含在Button
组件的 Prop 中。关于Button
组件的接口(interface)/类型的任何想法应如下所示 最佳答案
我以前使用过这种模式。声明component
类型的React.ComponentType<T> | string
属性。您的Button
组件应如下所示:
export interface ButtonProps {
component?: React.ComponentType<any>; // or React.ReactElement<any>["type"]
href?: string;
children?: React.ReactNode;
}
export function Button(props: ButtonProps) {
const {
component: Component = "button", // note: uppercase
children,
...other
} = props;
return (
<Component {...other}>
{children}
</Component>
);
}
关于javascript - 根据传递的 Prop 创建组件的类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55050901/