我如何让类型检查与 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 的响应的图像。这是我期望的打字稿错误。

在此处输入图片说明

约塞连船长

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

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 的文档。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何使用TypeScript在React Native中将ForwardRef与FunctionComponent一起使用

如何在 React 组件中使用 forwardRef?

将React forwardRef与Typescript通用JSX参数一起使用

如何在React Native中使用React.forwardRef()

使用forwardRef创建的React组件上的类型错误

如何在打字稿中将 useEffect 与 forwardRef 一起使用?

如何在基于类的组件中使用React.forwardRef?

如何在 React Native 的功能组件中使用 forwardRef?

React.ForwardRef TypeScript组件类型错误

我该如何使Intro js与React一起使用?

无法在React最终形式中使用forwardRef

如何使用ForwardRefRenderFunction导出forwardRef

如何使React Portal与React Hook一起使用?

将forwardRef与proptypes和eslint一起使用

在TypeScript中将forwardRef组件与子代一起使用

React useState钩子如何与可变对象一起使用

如何在React中将PropTypes与Typescript一起使用

如何将Jest与React Native一起使用

React Context:如何将其与对象一起使用

withSyles HOC在通过React.forwardRef时不会与其他道具一起传递innerRef

使用react-router-dom时如何通过路由传递forwardRef

返回输入或textArea的元素的React / Typescript forwardRef类型

到底为什么我们需要React.forwardRef?

如何使useRouteMatch与React-Router中的类型一起使用

在React.forwardRef中使用ref.current

直接在render函数中使用React.forwardRef

使用React.forwardRef与自定义ref属性的价值

TS/React 使用 forwardRef 将 ref 传递给组件

我如何在React中一起使用'update'和setState(prevState)?