【问题标题】:Access props inside the styled component using MUI使用 MUI 访问样式化组件内的道具
【发布时间】:2021-12-09 14:57:51
【问题描述】:

我正在尝试在 React JS 项目中使用 MUI 创建自定义按钮组件。我检查了文档,发现我可以使用样式组件来做到这一点。一切都与下面提供的代码配合良好。问题是我想创建一个更“可定制”的组件。我的主题文件中有 2 组颜色(主要和次要)。事实是我想创建一个能够为这组颜色(主要/次要)获取道具的按钮。

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

问题是:如何在样式化的组件代码中包含这个道具?

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    传递回调。在这个回调中,第一个参数是样式组件的道具。您还可以使用样式对象代替模板字符串。 this 答案中的更多详细信息。

    const CustomButtonRoot = styled("button")(
      ({ theme, myColor }) => `
      padding: 15px 20px;
      border-radius: 10px;
      color: ${myColor}; 
    `
    );
    
    <CustomButton myColor="red">abc</CustomButton>
    

    【讨论】:

    • 它运作良好,但我有一个小问题。我在我的组件上收到此错误:Type '{ children: string; btnColor:“次要”; }' 不可分配给类型 'IntrinsicAttributes & TodoButtonProps'。类型'IntrinsicAttributes & TodoButtonProps'.ts(2322) 上不存在属性'children'
    • @CătălinAvasiloaie 查看我的代码和框演示。
    猜你喜欢
    • 1970-01-01
    • 2021-09-22
    • 2022-01-18
    • 2018-09-21
    • 2021-08-24
    • 1970-01-01
    • 2021-05-28
    • 2019-04-13
    • 2018-05-18
    相关资源
    最近更新 更多