首页 > 解决方案 > 如何让类型检查与 React forwardRef 一起使用

问题描述

我在使用 forwardRef 时无法进行类型检查。我的代码如下:

零件:

export interface Props {
  label?: string;
  callback: () => void;
}

export const _Button = (props: Props) => {

  return (
    <div>
      <p>test</p>
    </div>
  );
};

export const Button = React.forwardRef((props, ref) => {
  return <_Button { ...props } forwarded={ref} />
});

组件用法:

export const App = () => {

  return (
    <div>
      <h1>Application</h1>
      <Button label="foo" />
    </div>
  );
};

您可以看到我没有传递所需的回调道具,但打字稿没有看到问题。以下是我尝试过的,但我仍然无法进行类型检查。

export interface Props {
  label?: string;
  callback: () => void;
}

export const _Button = (props: Props) => {

  return (
    <div>
      <p>test</p>
    </div>
  );
};

export const Button = React.forwardRef<HTMLButtonElement, Props>((props: Props, ref) => {
  return <_Button { ...props } forwarded={ref} />
});

任何帮助,将不胜感激。谢谢。

添加图像以响应答案 1 和 2。这是我预计会遇到的打字稿错误。

在此处输入图像描述

标签: reactjstypescript

解决方案


我假设你想做这样的事情:

import React, { FC, forwardRef, ForwardedRef, createRef } from 'react'

export interface Props {
    label?: string;
    callback: () => void;
    forwardedRef: ForwardedRef<HTMLDivElement>
}

export const _Button: FC<Props> = (props: Props) => {


    return (
        <div ref={props.forwardedRef}>
            <p>test</p>
        </div>
    );
};

export const Button = forwardRef<
    HTMLDivElement,
    Omit<Props, 'forwardedRef'>
>((props, ref) => <_Button {...props} forwardedRef={ref} />);


export const App = () => {
    const ref = createRef<HTMLDivElement>();

    return (
        <div>
            <h1>Application</h1>
            <Button ref={ref} label="foo" callback={() => null} />
        </div>
    );
};

在这里您可以找到有关 refs 的文档。


推荐阅读