React+TypeScript中如何正确集成otherProps消除组件类型错误?
解决TypeScript中InputComponent的属性类型错误问题
你的问题出在组件的Props接口定义上——你把disabled、className这类原生输入框属性塞进了单独的otherProps字段,但使用组件时是直接传递这些属性,TypeScript自然识别不了。
正确的做法是把自定义属性和原生HTML输入元素的属性合并,而不是单独定义otherProps:
步骤1:修改Props接口
用交叉类型(&)把自定义属性和React.InputHTMLAttributes<HTMLInputElement>合并,这样所有原生输入框属性都会被TypeScript识别:
import React from 'react'; import TextField from '@mui/material/TextField'; // 假设你用的是Material UI的TextField // 合并自定义属性和原生输入框属性 interface InputComponentProps { id: string; name: string; type: string; formik: any; // 建议替换成Formik的具体类型,比如FormikProps<YourFormValues> } & React.InputHTMLAttributes<HTMLInputElement>;
步骤2:调整组件参数解构
不需要单独的otherProps,直接用剩余参数接收所有原生属性:
export default function InputComponent({ id, name, type, formik, ...rest // 接收所有原生属性,比如disabled、className等 }: InputComponentProps) { return ( <TextField id={id} type={type} value={formik.values[name]} onChange={formik.handleChange} onBlur={formik.handleBlur} error={formik.touched[name] && !!formik.errors[name]} {...rest} // 把原生属性传递给内部TextField /> ); }
为什么这样能解决问题?
- 交叉类型让
InputComponentProps同时包含你自定义的id/name/type/formik,以及所有原生输入框的属性(比如disabled、className、placeholder等)。 - 使用剩余参数
...rest接收原生属性,再传递给内部的TextField,既符合TypeScript的类型检查,又能正确传递属性。
另外建议把formik: any替换成具体的Formik类型,比如FormikProps<YourFormValues>,这样能获得更好的类型提示,避免any带来的隐患。
内容的提问来源于stack exchange,提问作者AVT
相关产品推荐
相关产品推荐

