[英]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.