【问题标题】:React.ForwardRef TypeScript Component Type ErrorReact.ForwardRef TypeScript 组件类型错误
【发布时间】:2020-06-16 07:34:01
【问题描述】:

我有一个 Block 组件,它将根据 prop 值呈现 diva 标签。我想将父组件的 ref 传递给该组件。因此,我需要使用RefForwardingComponent 类型作为我的组件变量类型,但我收到HTMLAnchorElementHTMLDivElement 之间类型不兼容的错误。我该如何解决? here's the component code on CodeSandBox:

import * as React from "react";

interface Props {
  isLink: boolean;
}

type PropsWithElementProps<T> = React.HTMLProps<T> & Props;

type RefComponent<T, U> =
  | React.RefForwardingComponent<T, PropsWithElementProps<T>>
  | React.RefForwardingComponent<U, PropsWithElementProps<U>>;

// error for Block variable type... full error on CodeSandBox link
const Block: RefComponent<HTMLAnchorElement, HTMLDivElement> = React.forwardRef(
  ({ isLink }, ref) => {
    if (isLink)
      return (
        <a ref={ref} href="#nothing">
          I'm a link!
        </a>
      );
    else return <div ref={ref}>I'm a div!</div>;
  }
);

export default Block;

【问题讨论】:

标签: reactjs typescript


【解决方案1】:

React.forwardedRef 期望您为返回的元素和道具提供类型,以防无法推断。你可以这样表示:

import * as React from "react";

interface Props {
  isLink?: boolean;
}

const Block = React.forwardRef<HTMLAnchorElement & HTMLDivElement, Props>(
  ({ isLink = false }, ref) => {
    return isLink ? (
      <a ref={ref} href="#nothing">
        {"I'm a link!"}
      </a>
    ) : (
      <div ref={ref}>{"I'm a div!"}</div>
    );
  }
);

export default Block;

forwardRef 类型定义如下所示:

function forwardRef<T, P = {}>(render: ForwardRefRenderFunction<T, P>): ForwardRefExoticComponent<PropsWithoutRef<P> & RefAttributes<T>>;

【讨论】:

  • 非常感谢!这是有效的。你能再解释一下吗?当我的组件只返回其中一个时,为什么要结合 HTMLAnchorELEment 和 HTMLDivElement 的类型?为什么它不应该是 HTMLAnchorElement | HTMLDivElement?
猜你喜欢
  • 2019-01-09
  • 2019-08-17
  • 2021-02-18
  • 2021-06-04
  • 2016-02-22
  • 1970-01-01
  • 2019-03-27
  • 2022-11-25
  • 2016-10-09
相关资源
最近更新 更多