使用MUI LoadingButton组件传递Props时遇到TypeScript问题
当你基于MUI LoadingButton封装自定义组件时,无需用类型断言绕过类型检查,通过正确扩展组件Props类型就能解决传递自定义Props的类型问题,以下是两种最优实现方式:
方式一:扩展LoadingButtonProps定义自定义类型
直接继承LoadingButtonProps并添加你的自定义属性,让TypeScript自动识别所有合法Props:
import { LoadingButton, LoadingButtonProps } from '@mui/lab/LoadingButton'; // 定义包含自定义属性的组件Props类型 interface CustomLoadingButtonProps extends LoadingButtonProps { // 这里添加你的自定义Props,示例: customTip?: string; } const CustomLoadingButton = ({ customTip, ...restProps }: CustomLoadingButtonProps) => { // 在这里使用自定义属性,比如根据customTip做逻辑处理 return <LoadingButton {...restProps} />; };
方式二:泛型兼容更复杂的Props场景
如果你的组件需要支持动态Props或者更灵活的扩展,用泛型来约束Props类型:
import { LoadingButton, LoadingButtonProps } from '@mui/lab/LoadingButton'; // 泛型组件,同时支持LoadingButton原生Props和自定义Props const CustomLoadingButton = <P extends LoadingButtonProps>( props: P & { customTip?: string } ) => { const { customTip, ...restProps } = props; // 组件逻辑处理 return <LoadingButton {...restProps} />; };
这两种方式都能让TypeScript正确校验所有传入的Props,既保留LoadingButton的原生能力,又能安全传递自定义属性,完全替代类型断言的临时方案。
内容的提问来源于stack exchange,提问作者Maciek Winiarski
相关产品推荐
相关产品推荐

