React TypeScript封装MUI组件时如何正确拆分自定义Props?
解决方法
1. 直接解构拆分Props
最简洁的方式是通过对象解构,把自定义属性从传入的Props中分离出来,剩下的属性直接传给TextField:
import { TextField, TextFieldProps } from '@mui/material'; type PinnableTextFieldProps = TextFieldProps & { pinned: boolean; onPin: (newValue: boolean) => void; }; export function PinnableTextField({ pinned, onPin, ...textFieldProps }: PinnableTextFieldProps) { // 这里可以使用pinned和onPin实现自定义逻辑,比如渲染固定按钮 return ( <TextField {...textFieldProps} InputProps={{ ...textFieldProps.InputProps }} // 注意如果要保留原InputProps,需要合并而不是覆盖 /> ); }
为什么类型断言没用?
你之前用...(props as TextFieldProps)只是在TypeScript层面做了类型标注,但运行时pinned和onPin依然会被当作属性传递给TextField组件,React会检测到未知属性并抛出警告。类型断言不会修改实际的对象结构,只是告诉TS编译器“相信我,这个对象符合目标类型”。
2. 封装工具函数提取合法Props(适合自定义属性较多的场景)
如果后续要添加更多自定义属性,可以封装一个工具函数来过滤出TextField支持的属性:
import { TextField, TextFieldProps } from '@mui/material'; type PinnableTextFieldProps = TextFieldProps & { pinned: boolean; onPin: (newValue: boolean) => void; }; function getValidTextFieldProps(props: PinnableTextFieldProps): TextFieldProps { const { pinned, onPin, ...validProps } = props; return validProps; } export function PinnableTextField(props: PinnableTextFieldProps) { const validProps = getValidTextFieldProps(props); return ( <TextField {...validProps} InputProps={{ ...validProps.InputProps }} /> ); }
额外提示
注意你代码里的InputProps={{}}会覆盖用户传入的InputProps,如果需要保留用户设置的InputProps,一定要用扩展运算符合并,比如InputProps={{ ...textFieldProps.InputProps, /* 你的自定义Input属性 */ }}。
内容的提问来源于stack exchange,提问作者Noah
相关产品推荐
相关产品推荐

