如何修复React TypeScript中“Property 'focus' does not exist on type 'string'”错误
问题修复方案
你遇到的错误根源有两个:
- useRef的类型和初始化错误:你把
checkInfo初始化为空字符串,TypeScript就推断它的类型是string,自然没有focus()方法——focus()是DOM元素的方法,不是字符串的。 - 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
相关产品推荐
相关产品推荐

