[英]How to use React.forwardRef with TypeScript when using different html elements in the render
我正在努力使用根据道具显示跨度或<br>
非常简单的组件:
import * as React from 'react';
type Props = {value: string}
function LetterRenderer({value = ''}: Props, ref: React.Ref<HTMLElement>) {
switch(value) {
case '\n': return (<br ref={ref} />);
default: return (<span ref={ref}>{value}</span>);
}
}
const Letter = React.forwardRef<HTMLElement, Props>(LetterRenderer);
Letter.displayName = 'Letter';
export default Letter;
在<br ref={ref} />
,第二个ref
带有以下错误消息下划线:
Type 'Ref<HTMLElement>' is not assignable to type 'string | ((instance: HTMLBRElement | null) => void) | RefObject<HTMLBRElement> | null | undefined'.
Type 'RefObject<HTMLElement>' is not assignable to type 'string | ((instance: HTMLBRElement | null) => void) | RefObject<HTMLBRElement> | null | undefined'.
Type 'RefObject<HTMLElement>' is not assignable to type 'RefObject<HTMLBRElement>'.
Property 'clear' is missing in type 'HTMLElement' but required in type 'HTMLBRElement'.ts(2322)
lib.dom.d.ts(6336, 5): 'clear' is declared here.
index.d.ts(106, 9): The expected type comes from property 'ref' which is declared here on type 'DetailedHTMLProps<HTMLAttributes<HTMLBRElement>, HTMLBRElement>'
我应该如何解决这个问题?
function LetterRenderer({value = ''}: Props, ref: React.Ref<HTMLElement>) {
// ...
你的 ref prop 接受HTMLElement
但你真正想要的是HTMLBRElement | HTMLSpanElement
HTMLBRElement | HTMLSpanElement
因为ref
被传递到<br>
和<span>
,它们的ref
属性分别是React.Ref<HTMLBRElement>
和React.Ref<HTMLSpanElement>
。
将 ref 属性更改为
ref: React.Ref<HTMLBRElement | HTMLSpanElement>
请注意, HTMLBRElement
和HTMLSpanElement
都继承了HTMLElement
但不是相反; HTMLElement
没有clear
属性,但HTMLBRElement
有。
因为<br>
和<span>
的ref
属性分别只接受React.Ref<HTMLBRElement>
和React.Ref<HTMLSpanElement>
,所以需要相应地对ref
进行内联转换。
<br ref={ref as React.Ref<HTMLBRElement>} />
<span ref={ref as React.Ref<HTMLSpanElement>}>{text}</span>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.