【问题标题】:Material-UI: customizing Box component with withStylesMaterial-UI:使用 withStyles 自定义 Box 组件
【发布时间】:2020-08-10 12:29:40
【问题描述】:

我习惯使用 withStyles 快捷方式自定义 MUI 组件,但是当我使用 Box 执行此操作时,它会在 DOM 中为我提供“classes=[object Object]”属性。但是,组件在应用自定义后按预期工作。

const SplitBoxStyle = {
  root: {
    backgroundColor: '#eaeaea',
    width: 1,
    height: 24,
    marginRight: 5
  }
}
const SplitBox = withStyles(SplitBoxStyle)(Box)

export const () => {
  return <Box>Here is styled box: <SplitBox /></Box>
}

它提供 HTML:

<div class="MuiBox-root MuiBox-root-122 Styled(MuiBox)-root-87" classes="[object Object]" style="margin-left: 8px; margin-right: 15px;"></div>

那么这样是错的吗?或者如何去除这些烦人的类属性?

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    这里有一点修改的代码。

    import React from "react";
    import { withStyles } from "@material-ui/core/styles";
    import Box from "@material-ui/core/Box";
    
    const SplitBoxStyle = {
      root: {
        backgroundColor: "#eaeaea",
        width: 100,
        height: 100,
        marginRight: 5
      }
    };
    
    function SplitBox(props) {
      const { classes } = props;
      return <Box className={classes.root}>Here is styled box</Box>;
    }
    
    export default withStyles(SplitBoxStyle)(SplitBox);
    

    这里是code sandbox。

    【讨论】:

    • 谢谢,我已经结束了: const SplitBox = withStyles(SplitBoxStyle)(({ classes, children, ...props }) => {children})
    • 我遇到了同样的问题,但是这个解决方案不适用于 Typescript。编译器发出关于 classes 属性的警告。知道在这种情况下如何解决它吗?
    • 刚刚找到方法并添加了替代答案。 ;)
    【解决方案2】:

    使用 TypeScript 时,必须声明自定义接口以允许使用 classes 属性。这样:

    import React from "react";
    import { StyledComponentProps, withStyles } from "@material-ui/core/styles";
    import { Box, BoxProps } from "@material-ui/core";
    
    interface Props extends BoxProps, StyledComponentProps {}
    
    function SplitBox({ classes, children, ...props }: Props) {
      return <Box className={classes?.root} {...props}>{children}</Box>;
    }
    
    export default withStyles(SplitBoxStyle)({
      root: {
        backgroundColor: "#eaeaea",
        width: 100,
        height: 100,
        marginRight: 5
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2021-12-07
      • 2020-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-06
      • 2019-10-11
      • 1970-01-01
      相关资源
      最近更新 更多