如何在MUI的styled组件中访问props实现自定义按钮动态配色?
修正方案
你需要调整styled组件的参数接收逻辑和props透传规则,完整可运行的代码如下:
import * as React from 'react'; import ButtonUnstyled, { ButtonUnstyledProps, } from '@mui/core/ButtonUnstyled'; import { styled } from '@mui/system'; import { theme } from '../../theme'; // 声明styled组件接收的自定义属性类型 interface CustomButtonRootProps { type?: 'primary' | 'secondary' } const CustomButtonRoot = styled('button', { // 配置自定义属性不渲染到原生DOM,避免控制台警告 shouldForwardProp: (prop) => prop !== 'type', })<CustomButtonRootProps>(({ type = 'primary' }) => ` background-color: ${theme.palette[type].main}; padding: 15px 20px; border-radius: 10px; color: #fff; `); // 自定义按钮属性继承无样式按钮的所有原生属性,再加自定义type属性 interface TodoButtonProps extends ButtonUnstyledProps { type?: 'primary' | 'secondary' } function CustomButton(props: TodoButtonProps) { return <ButtonUnstyled {...props} component={CustomButtonRoot} />; } export default CustomButton
使用方式
直接在调用组件时传入type属性即可动态切换配色:
<CustomButton type="primary">主按钮</CustomButton> <CustomButton type="secondary">次按钮</CustomButton> // 不传type默认使用primary配色 <CustomButton>默认按钮</CustomButton>
关键逻辑说明
- styled组件需要通过泛型声明自定义属性的类型,样式部分用函数接收传入的props,才能动态计算样式值,不能直接使用静态模板字符串
shouldForwardProp配置用于过滤自定义属性,避免把type渲染到原生button的DOM标签上,触发未知属性的控制台警告- 给
type设置默认值primary,未传参数时也能正常渲染 TodoButtonProps继承ButtonUnstyledProps后,所有无样式按钮支持的属性(如disabled、onClick等)都可以直接在CustomButton上使用,不需要额外透传
内容的提问来源于stack exchange,提问作者Cătălin Avasiloaie
相关产品推荐
相关产品推荐

