简体   繁体   English

React +TypeScript - 呈现动态元素问题的组件

[英]React +TypeScript - component that renders a dynamic element issue

I feel like I'm pretty close but I can't take my compiler screaming at me anymore!我觉得我已经很接近了,但我不能再让我的编译器对我尖叫了!

The problem seems to be arising with passing the ref, when div is in the as union.divas联合中时,传递 ref 似乎会出现问题。

When div is removed as a possible element to render, all my errors disappear:div作为可能的渲染元素被删除时,我所有的错误都消失了:

Sandbox: https://codesandbox.io/s/modest-cherry-udfg3沙盒: https://codesandbox.io/s/modest-cherry-udfg3

typescript


export interface BoxProps extends React.HTMLAttributes<HTMLElement> {
  /** The element to render */
  as: 'div' | 'section' | 'article' | 'aside' | 'header' | 'footer'
  /** The children to display */
  children?: React.ReactNode
  /** The ref to forward  */
  forwardRef?: React.RefObject<HTMLElement>
}

export function Box({ children, className, style, as: As, forwardRef, ...htmlProps }: BoxProps) {
  return (
    <As style={{ ...style }} className={cn('Box', className)} ref={forwardRef} {...htmlProps}>
      {children}
    </As>
  )
}

Since HTMLDivElement extends HTMLElement , you could simply use由于HTMLDivElement扩展了HTMLElement ,您可以简单地使用

forwardRef?: React.RefObject<HTMLDivElement>

to get rid of the compiler screams.摆脱编译器的尖叫声。

However, this solution looks a bit odd since as is not supposed to be exclusively a div element.然而,这个解决方案看起来有点奇怪,因为as不应该是一个div元素。

To make code clearer, you could use an intersection type to combine HTMLElement with HTMLDivElement为了使代码更清晰,您可以使用交集类型HTMLElementHTMLDivElement结合起来

forwardRef?: React.RefObject<HTMLElement & HTMLDivElement>

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

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