gpt4 book ai didi

javascript - 在渲染中使用不同的 html 元素时如何将 React.forwardRef 与 TypeScript 结合使用

转载 作者:行者123 更新时间:2023-12-02 19:39:57 30 4
gpt4 key购买 nike

我正在努力处理那个显示跨度或 <br> 的非常简单的组件。取决于 Prop :

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 属性接受 HTMLElement但你真正想要的是 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>

关于javascript - 在渲染中使用不同的 html 元素时如何将 React.forwardRef 与 TypeScript 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60403276/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com