reactjs - 使用 MUI 访问样式组件内的 props

标签 reactjs material-ui

我正在尝试在 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>

Codesandbox Demo

关于reactjs - 使用 MUI 访问样式组件内的 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69685777/

相关文章:

javascript - 如何解决 DOM 元素上的警告 : React does not recognize the `currentSlide` , ` slideCount` Prop

reactjs - kepler.gl 状态不存在。您可能忘记在根 reducer 中安装 keplerGl reducer

javascript - 响应 header 为空

javascript - 清除Textfield Material -ui ReactJS

javascript - 如何更改 Material-UI Select Field HR 元素的颜色?

javascript - 在不使用填充的情况下向 Material UI 网格添加空白列

reactjs - 需要更清楚的解释如何避免使用 React hooks 无限重新渲染

reactjs - MuiThemeProvider 中的错误

css - Material UI - 选择下划线颜色

javascript - 如何避免嵌套的三元运算符