【问题标题】:How to type a prop that gets rendered as dynamic component HTML Element如何键入一个呈现为动态组件 HTML 元素的道具
【发布时间】:2022-11-29 01:22:33
【问题描述】:

如何键入一个组件,该组件接受一个有效的 html 元素标签名称作为 prop 以动态呈现它

interface ButtonProps {
  children: ReactNode;
  className?: string;
  as?: string; <--- ?
  [key: string]: unknown;
}


const Button = forwardRef({ children, as: Component = 'button', children, ...props}: ButtonProps), ref) => (
  <Component ref={ref} className={className} {...props}>
    {children}
  </Component>

)

当前收到打字稿错误Property 'children' does not exist on type 'IntrinsicAttributes'.,这绝对有道理。

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    您可以按如下方式键入:

    interface ButtonProps {
      children: ReactNode;
      className?: string;
      as?: string;
      [key: string]: unknown;
    }
    
    const Button = forwardRef<HTMLDivElement, ButtonProps>(
      (props, ref) => {
        return (
          <Component ref={ref}>
            {props.children}
          </Component>
        );
      }
    );
    
    export default Button;
    

    第一个类型参数用于ref,其他类型参数用于props,这有点令人困惑。

    【讨论】:

      猜你喜欢
      • 2019-04-03
      • 2019-01-25
      • 2020-07-23
      • 2020-12-22
      • 1970-01-01
      • 2017-03-25
      • 2020-05-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多