网站搜索

reactjs - 在 TypeScript 中使用动态标签名称的 ref


我有一个组件,其动态标签名可以是 div 或 fieldset,这取决于从我们的 useForm 钩子返回的 group 属性的值。

const FormGroup = React.forwardRef<
  HTMLFieldSetElement | HTMLDivElement,
  React.HTMLAttributes<HTMLFieldSetElement | HTMLDivElement>
>(({ children, className, ...props }, ref) => {
  const { group } = useForm();
  const Component = group ? "fieldset" : "div";

  return (
    <Component ref={ref} className={className} {...props}>
      {children}
    </Component>
  );
});

但是它返回错误,提示 ref 不能赋值... 我尝试使用了:

const Component = group ? "fieldset" : "div" as keyof JSX.IntrinsicElements;

有没有一种干净的方法来对使用 ref 的动态标签名进行类型检查?

答案#1

这是我的方法

import {
  ElementType,
  FC,
  HTMLAttributes,
  Ref,
  forwardRef,
  useRef,
} from "react";

interface ComponentProps extends HTMLAttributes<HTMLElement> {
  as?: ElementType;
  ref: Ref<HTMLElement>;
}

const Component: FC<ComponentProps> = forwardRef(
  ({ as: Tag = "div", children, ...otherProps }, ref) => {
    return (
      <Tag {...otherProps} ref={ref}>
        {children}
      </Tag>
    );
  }
);

const App: FC = () => {
  const myRef = useRef<HTMLElement>(null);
  const group: "div" | "fieldset" = "div";
  return (
    <>
      <div>App</div>
      <Component as={group} ref={myRef}>
        <p>This is the component's content</p>
      </Component>
    </>
  );
};

export default App;