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

React+TypeScript中useRef报错Property 'value'不存在于type 'never'如何解决

报错原因

你在声明useRef(null)时未指定泛型类型,TypeScript无法推断inputRef.current的实际类型,会默认将其推导为never类型,访问never类型上的任何属性都会抛出 Property 'value' does not exist on type 'never' 错误。

修复方案
  • 给useRef添加HTMLInputElement泛型声明,明确该ref指向原生input元素:
// 把原来的 const inputRef = useRef(null); 替换成下面的代码
const inputRef = useRef<HTMLInputElement>(null);
  • 务必将声明好的inputRef绑定到组件内的input标签上,避免current一直为null:
<input
  ref={inputRef}
  // 保留你input原有的其他属性,比如name、placeholder、事件绑定等
/>
补充说明

泛型<HTMLInputElement>明确了ref的指向类型,TypeScript会识别到该类型下存在value属性,结合你原有的可选链?.语法,就能合法判断输入框的填充状态,同时兼容current初始为null的场景。

内容的提问来源于stack exchange,提问作者João Pedro Reis De Mello

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 03:24:00