React TS自定义Input组件报错:Property 'onBlur'不存在于目标类型
解决React TypeScript自定义Input组件的onBlur类型错误
问题原因
你自定义的InputProps接口未包含原生<input>元素的onBlur等事件属性,导致TypeScript在合并组件属性类型(IntrinsicAttributes & InputProps & RefAttributes<HTMLInputElement>)时,无法找到onBlur的定义。
修复方案
方案1:继承React内置输入属性类型(推荐)
让InputProps直接继承React.InputHTMLAttributes<HTMLInputElement>,自动获取所有原生input的属性(包括onBlur、onChange等事件),同时可按需添加自定义属性:
interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> { // 此处添加你的自定义属性,例如: label?: string; errorMessage?: string; }
方案2:手动声明onBlur属性类型
若不需要全部原生属性,可在InputProps中单独声明onBlur的类型:
interface InputProps { // 你的自定义属性 label?: string; // 手动添加onBlur的类型定义 onBlur?: React.FocusEventHandler<HTMLInputElement>; // 其他需要的原生属性可同理添加 }
组件实现示例(基于方案1)
import React, { forwardRef } from 'react'; interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> { label?: string; } const Input = forwardRef<HTMLInputElement, InputProps>(({ label, ...rest }, ref) => { return ( <div> {label && <label>{label}</label>} <input ref={ref} {...rest} /> </div> ); }); export default Input;
使用示例
// 此时使用onBlur不会触发类型错误 <Input label="用户名" onBlur={(e) => { console.log('输入框失去焦点:', e.target.value); }} />
验证效果
修复后,TypeScript将不再提示Property 'onBlur' does not exist on type 'IntrinsicAttributes & InputProps & RefAttributes<HTMLInputElement>'的错误,因为InputProps已包含onBlur的合法类型定义。
内容的提问来源于stack exchange,提问作者Sai Sumanth Lokinindi
相关产品推荐
相关产品推荐

