ref 在 HTMLAttributes 中不可用<HTMLDivElement>

问题描述 投票:0回答:1

我有一个可重复使用的包装组件,如下所示:

import { FC, HTMLAttributes } from "react";

const Wrapper: FC<HTMLAttributes<HTMLDivElement>> = ({
  children,
  className,
  ...props
}) => (
  <div className={`h-[90vh] ${className ? className : ""}`} {...props}>
    {children}
  </div>
);

export default Wrapper;

但是我无法将

ref
属性添加到组件中。

<Wrapper ref={ref} ...

Property 'ref' does not exist on type 'IntrinsicAttributes & HTMLAttributes<HTMLInputElement>'.

我应该为

Wrapper
组件使用什么 typescript 类型并添加 ref 属性而不出现错误?

javascript reactjs typescript ref
1个回答
0
投票

如果您想使用

FC
类型,那么您需要使用
ComponentPropsWithRef<"div">
类型作为道具。 (不要忘记将组件包裹在
forwardRef
中,否则 ref 将不起作用)

或者,您可以省略

FC
类型,只定义组件,如下所示:

import React, { forwardRef, ComponentPropsWithoutRef } from "react";

const Wrapper = forwardRef<HTMLDivElement, ComponentPropsWithoutRef<"div">>(({
  children,
  className,
  ...props
}, ref) => (
  <div ref={ref} className={`h-[90vh] ${className ? className : ""}`} {...props}>
    {children}
  </div>
));

这样您就可以将 ref 传递给组件并对其进行类型检查。

© www.soinside.com 2019 - 2024. All rights reserved.