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

如何修复React TypeScript中“Property 'focus' does not exist on type 'string'”错误

问题修复方案

你遇到的错误根源有两个:

  1. useRef的类型和初始化错误:你把checkInfo初始化为空字符串,TypeScript就推断它的类型是string,自然没有focus()方法——focus()是DOM元素的方法,不是字符串的。
  2. ref绑定方式错误:你用了字符串ref={"checkInfo"},这是React已经废弃的旧写法,而且根本没法和你创建的useRef实例关联起来。

修复后的代码

import { useRef, useState } from "react"

const UseRefMethod = () => {
    const [name, setName] = useState("Prabhjot")
    // 指定ref类型为HTMLInputElement | null,初始化为null
    const checkInfo = useRef<HTMLInputElement | null>(null)
    const reset = () => {
        setName("")
        // 加非空断言确保current不是null,或者用checkInfo.current?.focus()
        checkInfo.current!.focus()
    }
    console.log(checkInfo)
    return(
        <>
        {name}
        {/* 直接把useRef实例传给ref属性 */}
        <input ref={checkInfo} type="text" value={name} onChange={(e)=>setName(e.target.value)}></input>
        <button onClick={reset}>Reset</button>
        </>
    )
}
export default UseRefMethod

关键修改点说明

  • useRef类型声明:<HTMLInputElement | null>明确告诉TypeScript这个ref是用来关联input元素的,初始值设为null(因为组件挂载前ref还没关联到DOM)。
  • ref绑定:直接把checkInfo传给input的ref属性,这样React会在组件挂载后把input的DOM元素赋值给checkInfo.current。
  • 调用focus的安全处理:用!非空断言是因为我们确定点击reset按钮时input已经挂载,current肯定有值;如果担心边界情况,也可以用可选链checkInfo.current?.focus(),这样当current为null时会静默跳过,不会报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 18:03:14