簡體   English   中英

在渲染中使用不同的 html 元素時如何將 React.forwardRef 與 TypeScript 一起使用

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

請注意, HTMLBRElementHTMLSpanElement都繼承了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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM