React.ForwardRef TypeScript组件类型错误

时间:2020-03-03 20:55:52

标签: reactjs typescript

我有一个Block组件,它将根据prop值呈现一个diva标签。我想将引用从父组件传递到此组件。因此,我需要对组件变量类型使用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;

1 个答案:

答案 0 :(得分:3)

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>>;