React Material TextField中如何正确传递{...rest} props?
Material UI TextField包装组件在TypeScript中传递剩余Props的问题
我在包装组件中使用Material UI的TextField,在JS文件中传递{...otherprops}这类剩余Props时运行正常,但在TypeScript中出现报错。
初始代码如下:
const TextFieldWrapper = (props: FormFieldProps) => { const {name, type, valid,touched, errorMessage, ...otherprops} = props; return ( <> <TextField name={name} type={type} variant= 'outlined' {...otherprops}/> {!valid && touched && <ErrorMessage>{errorMessage}</ErrorMessage>} </> ); }
报错原因是自定义的FormFieldProps类型未与Material UI TextField的官方Props类型对齐,导致TypeScript判定剩余Props不符合TextField的接收要求。
我曾尝试用inputProps解决该报错,但运行应用时Props并未生效,代码如下:
const TextFieldWrapper = (props: FormFieldProps) => { const {name, type, valid,touched, errorMessage, ...otherprops} = props; console.log(props); const inputProps = { otherprops:{...otherprops} }; return ( <> <TextField name={name} type={type} variant= 'outlined' inputProps={inputProps} /> {!valid && touched && <ErrorMessage>{errorMessage}</ErrorMessage>} </> ); }
正确解决方法
1. 对齐类型定义(推荐)
让自定义的FormFieldProps扩展Material UI TextField的官方Props类型,同时保留自定义字段:
import { TextFieldProps } from '@mui/material/TextField'; type FormFieldProps = TextFieldProps & { valid: boolean; touched: boolean; errorMessage: string; };
此时TypeScript会自动识别otherprops是TextField可接受的Props子集,类型检查通过。
2. 恢复原有传递方式
修正类型后,直接使用最初的展开写法即可正常运行:
const TextFieldWrapper = (props: FormFieldProps) => { const {name, type, valid, touched, errorMessage, ...otherprops} = props; return ( <> <TextField name={name} type={type} variant='outlined' {...otherprops}/> {!valid && touched && <ErrorMessage>{errorMessage}</ErrorMessage>} </> ); }
3. 临时类型断言(不推荐)
如果无法修改FormFieldProps的定义,可临时用类型断言绕过检查,但会损失TypeScript的类型安全保障:
<TextField name={name} type={type} variant='outlined' {...otherprops as TextFieldProps}/>
内容的提问来源于stack exchange,提问作者Praveen
相关产品推荐
相关产品推荐

