[英]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.当
div
在as
联合中时,传递 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
为了使代码更清晰,您可以使用交集类型将
HTMLElement
与HTMLDivElement
结合起来
forwardRef?: React.RefObject<HTMLElement & HTMLDivElement>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.