React TypeScript组件继承HTMLAttributes后部分属性传递报错
问题解决:Input组件无法接收disabled/required等属性
你的问题出在Props接口继承的类型选择上:React.HTMLAttributes<HTMLInputElement>仅包含通用HTML元素的属性(比如placeholder、className),而disabled、required这类input专属属性,属于React.InputHTMLAttributes<HTMLInputElement>的覆盖范畴,直接继承HTMLAttributes会遗漏这些input特有的属性。
修改方案非常直接,把Props接口的继承类型替换为InputHTMLAttributes即可:
import React from 'react'; interface InputFieldProps extends React.InputHTMLAttributes<HTMLInputElement> { customProp: string; } const InputField: React.FC<InputFieldProps> = ({ customProp, ...htmlProps }) => { return ( <input {...htmlProps} /> ); };
调整后,input元素支持的所有属性(包括disabled、required、type、value等)都能正常传递,同时保留你自定义的customProp。
内容的提问来源于stack exchange,提问作者DariusW
相关产品推荐
相关产品推荐

