JSX React 'div | p' 的类型是什么?

What is type for JSX React 'div | p'?

我正在构建一个自定义组件,我想将元素名称作为 prop 传递给组件,例如 divp;一个 HTMLElement

要注意的是它必须是块或内联元素

export const MyComponent = props => {
  const currentNode = useRef()
  const { tag: Comp } = props
  return <Comp ref={currentNode}>Strawberry Kisses!</Comp>
}

如您所见,我正在解构 prop 以获取 tag 值 (Component) 并将其作为元素传递。

目前,下面的接口会报错

Type '{ ref: MutableRefObject<undefined>; }' is not assignable to type 'IntrinsicAttributes'.
  Property 'ref' does not exist on type 'IntrinsicAttributes'.ts(2322)
interface MyProps extends React.ClassAttributes<MyComponent> {
  tag: string;
}

我需要基本检查一下 if (tag == HTMLElement && tag === JSX.IntrinsicElements) { return 'this is the correct type and allow it' }

如有任何帮助,我们将不胜感激。

据我所知,你的错误与你的问题无关。

要修复您的错误,您需要执行 <Comp ref={currentNode.current}>

您可能 运行 遇到的下一个错误是您没有将 tag 属性传递给您的子组件。

要真正回答你的问题,我认为 HTML 标签的所有名称没有任何 in-built 枚举或类型,所以你必须自己定义它,尤其是因为你似乎想要更具体的东西。