繁体   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