You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用React forwardRef时遭遇TypeScript类型错误求助

使用forwardRef解决React组件的TypeScript类型错误

问题代码

App.tsx

import { useRef, useState } from "react";
import InputField from "./InputField";
import "./styles.css";

export default function App() {
 
  const checkInRef = useRef<HTMLInputElement>(null);
  return (
      <InputField        
        ref={checkInRef}
      />
  );
}

InputField.tsx

import {
  Dispatch,
  SetStateAction,
  forwardRef,
} from "react";


const InputField = forwardRef<HTMLInputElement>(function (props, ref) {
  return (
    <div>
      <input ref={ref} />
      <button onClick={() => ref.current.focus()}>focus</button>
    </div>
  );
});
export default InputField;

出现的TypeScript错误

  • 'ref' is possibly 'null'.
  • Property 'current' does not exist on type '((instance: HTMLInputElement | null) => void) | MutableRefObject<HTMLInputElement | null>'. Property 'current' does not exist on type '(instance: HTMLInputElement | null) => void'.

解决方案(基于forwardRef)

forwardRef传入的ref参数类型是ForwardedRef<HTMLInputElement>,它可能是MutableRefObject实例,也可能是一个回调函数,因此不能直接访问.current;同时ref.current可能为null,需要先做非空判断。

修改InputField.tsx的点击事件处理逻辑,兼容两种ref类型并处理null值:

import { forwardRef, ForwardedRef } from "react";

const InputField = forwardRef<HTMLInputElement>((props, ref) => {
  const handleFocus = () => {
    // 处理MutableRefObject类型的ref
    if (ref && "current" in ref) {
      ref.current?.focus();
    } 
    // 处理回调类型的ref
    else if (typeof ref === "function") {
      const inputElement = document.querySelector("input");
      inputElement && ref(inputElement);
      inputElement?.focus();
    }
  };

  return (
    <div>
      <input ref={ref} />
      <button onClick={handleFocus}>focus</button>
    </div>
  );
});

export default InputField;

说明

  1. 通过"current" in ref判断ref是否为MutableRefObject,再用可选链?.处理ref.current为null的情况
  2. 额外处理了回调类型的ref,保证组件对两种ref传递方式都兼容
  3. 这样修改后,两个TypeScript错误会被消除,同时保留forwardRef的用法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 23:16:14