【问题标题】:What is type for JSX React 'div | p'?JSX React 'div | 的类型是什么? p'?
【发布时间】:2019-06-23 12:17:37
【问题描述】:

我正在构建一个自定义组件,我想将元素名称作为道具传递给组件,例如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 &amp;&amp; tag === JSX.IntrinsicElements) { return 'this is the correct type and allow it' }

任何方向的帮助表示赞赏。

【问题讨论】:

    标签: reactjs typescript interface react-props


    【解决方案1】:

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

    要修复您的错误,您需要执行&lt;Comp ref={currentNode.current}&gt;

    您可能会遇到的下一个错误是您没有将 tag prop 传递给您的子组件。

    要真正回答您的问题,我认为没有任何内置枚举或所有 HTML 标签名称的类型,因此您必须自己定义它,特别是因为您似乎想要更多的东西具体的。

    【讨论】:

    • 我最近看了一下,我认为枚举理论是正确的。他们在反应源文件中使用enum,所以我必须自己列一个列表。谢谢,朝着正确的方向迈出了一步。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    • 2020-06-07
    • 2021-09-27
    • 2023-01-01
    • 2017-10-09
    • 2017-07-23
    相关资源
    最近更新 更多