React+TypeScript如何复用ButtonProps属性,避免重复定义backgroundColor
解决方案
方法一:直接继承ButtonProps
如果希望TextButton能直接接收ButtonProps的所有属性,同时新增专属的textColor,可以让TextButtonProps继承ButtonProps,完全不用重复定义任何ButtonProps里的属性:
// 定义TextButtonProps interface TextButtonProps extends ButtonProps { textColor?: Colors; } // 组件使用 const TextButton = ({ backgroundColor, textColor = 'black', ...buttonProps // 包含ButtonProps中剩余的所有属性 }: TextButtonProps) => { return ( // 示例:将backgroundColor和其他属性传递给基础按钮组件 <Button backgroundColor={backgroundColor} {...buttonProps}> <span style={{ color: textColor }}>{buttonProps.children}</span> </Button> ); };
这种方式让TextButton的API更扁平,使用时不用嵌套buttonProps,直接像使用基础按钮一样传参,再加个textColor即可。
方法二:单独提取指定属性(保留buttonProps嵌套)
如果只想把backgroundColor单独作为TextButton的直接属性,同时保留buttonProps传递其他基础按钮属性,可以用TypeScript的Pick和Omit工具类型避免重复定义:
// 从ButtonProps提取backgroundColor,同时让buttonProps排除该属性 interface TextButtonProps extends Pick<ButtonProps, 'backgroundColor'> { buttonProps?: Omit<ButtonProps, 'backgroundColor'>; textColor?: Colors; } // 组件使用 const TextButton = ({ backgroundColor, textColor = 'black', buttonProps = {}, }: TextButtonProps) => { return ( // 合并backgroundColor与buttonProps传递给基础按钮 <Button backgroundColor={backgroundColor} {...buttonProps}> <span style={{ color: textColor }}>{buttonProps.children}</span> </Button> ); };
这样既不会重复定义backgroundColor,又能满足你直接解构它的需求,同时buttonProps里也不会出现重复的backgroundColor字段。
内容的提问来源于stack exchange,提问作者four-eyes
相关产品推荐
相关产品推荐

