You need to enable JavaScript to run this app. TypeScript如何在React高阶组件中正确使用useRef关联HTML元素
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript如何在React高阶组件中正确使用useRef关联HTML元素

报错根因

该类型报错是类型定义不匹配+React设计限制叠加导致的:

Type '{ name: string; type: string; value: string; ref: RefObject; }' is not assignable to type 'IntrinsicAttributes & TElementWithAttributes & { children?: ReactNode; }'. Property 'ref' does not exist on type 'IntrinsicAttributes & TElementWithAttributes & { children?: ReactNode; }'.

  • 你给高阶组件传入的Comp定义的类型是普通FC<TElementWithAttributes>,而React的标准类型体系中,普通函数组件类型本身就不包含可接收的ref属性,TypeScript自然会判定你传入的ref是组件上不存在的非法属性。
  • 你定义的TElementWithAttributes只覆盖了HTMLInputElement的属性,既没有兼容预留的HTMLTextAreaElement场景,也没有把ref指向的DOM实例类型和组件入参做绑定,泛型约束和实际使用需求完全不匹配。
具体修复方案
  • 第一步:重新定义传入组件的类型,补上ref的类型约束
    不要用不带ref支持的普通FC类型,换成支持ref透传的组件类型定义,同时兼容input和textarea两种元素的公共属性:

    import type {
      InputHTMLAttributes,
      TextareaHTMLAttributes,
      ForwardRefExoticComponent,
      RefAttributes,
    } from 'react';
    
    // 统一两种输入元素的类型
    type TElementType = HTMLInputElement | HTMLTextAreaElement;
    type TInputElementAttributes = InputHTMLAttributes<HTMLInputElement> 
      & TextareaHTMLAttributes<HTMLTextAreaElement>;
    // 传入的组件必须支持接收指向对应DOM元素的ref
    type TInputComponent = ForwardRefExoticComponent<
      TInputElementAttributes & RefAttributes<TElementType>
    >;
    

    注意:这是React的设计限制,不是类型定义的问题——普通函数组件本身没有可挂载ref的实例,只有通过React.forwardRef包裹的组件才能接收ref参数,将其绑定到内部的原生DOM节点上,否则运行时无论类型是否通过,refValue.current都会是null。

  • 第二步:重构高阶组件的泛型逻辑,避免类型写死
    原来的高阶组件把返回值的props写死成只有submitTouched,既没有透传传入组件的原有属性,也没有正确匹配ref的类型。调整为带泛型的高阶组件,在保留原有错误更新逻辑的同时修正类型绑定:

    const withInput = <P extends TInputElementAttributes>(Comp: TInputComponent) => {
      // 合并传入组件的原有props和高阶组件注入的props
      const WrappedInput: FC<P & Props> = (props) => {
        const { submitTouched, ...restComponentProps } = props;
        // ref类型和目标DOM元素保持一致
        const refValue = useRef<TElementType>(null);
    
        const updateErrors = (val: string) => {
          // 保留原有错误处理逻辑
        };
    
        useEffect(() => {
          if (submitTouched && refValue.current) {
            updateErrors(refValue.current.value);
          }
        }, [submitTouched]);
    
        // 正确透传原有属性和ref
        return <Comp {...restComponentProps} ref={refValue} />
      }
      return WrappedInput;
    };
    
  • 第三步:业务逻辑适配
    你原代码中给Comp硬编码了name="somename"、type="text"、value="somevalue"这些固定属性,实际使用时记得把这些硬编码值换成通过props透传的内容,避免覆盖原有组件的自定义配置。

兜底替代方案

如果业务场景中传入的组件没法改造为支持forwardRef的形式,也可以通过包裹一层原生容器元素的方式获取DOM节点:

  • 在高阶组件的返回值外层加一个无样式的div容器,给容器绑定ref,在effect中通过containerRef.current?.querySelector('input, textarea')拿到内部的输入元素实例读取value。
  • 这种方式不需要改造传入的组件,但相比直接透传ref会有轻微的性能开销,仅适合无法修改传入组件源码的兜底场景。

内容的提问来源于stack exchange,提问作者Inspiraller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.23 02:54:01