This question already has an answer here:
How do I type this 'as' JSX attribute in TypeScript?

(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/

10-11 23:54
查看更多