繁体   English   中英

如何使用基于`as` 的 props 动态创建 html 元素 on react (TypeScript)

[英]How to create html element dynamically with props based on `as` on react (TypeScript)

我想在我的函数中基于as={""}属性创建 a、b、div 或其他元素。

我检查as ,然后使用,如果卫士创建元素一个接一个。 但是有没有办法基于组件创建 html 元素?

我希望能够创建b, a, h4 h3或任何没有if的元素

我发现了类似的问题,但它使用了样式组件。 没有它可以做到吗?

目前我这样做:

import * as React from 'react'

interface Props {
  children: (React.ReactChild | React.ReactNode) | (React.ReactChild[] | React.ReactNode[])
  onClick?: (e) => void
  as?: string
}

const DynElement: React.FunctionComponent<Props> = props => {
  const { as , children } = props

  return (
  <>
    {as === 'div' && <div {...props_rest}>
      {children}
    </div>}
    {as === 'b' && <b {...props_rest}>
      {children}
    </b>}
    </>
  )
}

export default DynElement

用法是:

<DynElement as="b" onClick={...}>...</DynElement>

使用 TypeScript + React。

捕获as支柱在大写变量和使用,作为一个JSX组分:

const { as: Cmp = ‘div’, ...rest } = props;

return (
  <Cmp {...rest} />
);

甚至不需要明确地传递孩子。 它将与“休息”道具一起传递。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM