我正在尝试在 React JS 项目上使用 MUI 创建自定义按钮组件。我检查了文档,发现可以使用样式组件来做到这一点。一切都与下面提供的代码配合得很好。问题是我想创建一个更“可定制”的组件。我的主题文件中有 2 组颜色(主要和次要)。事实上,我想创建一个能够为这组颜色(主要/次要)提供 Prop 的按钮。
import * as React from 'react';
import ButtonUnstyled, {
buttonUnstyledClasses,
ButtonUnstyledProps,
} from '@mui/core/ButtonUnstyled';
import { styled } from '@mui/system';
import { theme } from '../../theme';
const CustomButtonRoot = styled('button')(`
background-color: ${theme.palette[props.type].main};
padding: 15px 20px;
border-radius: 10px;
color: #fff;
`);
interface TodoButtonProps {
unstyledProps: ButtonUnstyledProps,
type?: 'primary' | 'secondary'
}
function CustomButton(props: TodoButtonProps) {
return <ButtonUnstyled {...props} component={CustomButtonRoot} />;
}
export default CustomButton
问题是:如何在样式化组件代码中包含此 Prop ?
最佳答案
传递回调。在此回调中,第一个参数是样式组件的 props。您还可以使用样式对象代替模板字符串。更多详情请参阅this回答。
const CustomButtonRoot = styled("button")(
({ theme, myColor }) => `
padding: 15px 20px;
border-radius: 10px;
color: ${myColor};
`
);
<CustomButton myColor="red">abc</CustomButton>
关于reactjs - 使用 MUI 访问样式组件内的 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69685777/