【问题标题】:How to add padding and margin to all Material-UI components?如何为所有 Material-UI 组件添加填充和边距?
【发布时间】:2019-02-07 01:06:32
【问题描述】:

我需要为一些 Material-UI 组件添加内边距或边距,但找不到简单的方法来做到这一点。我可以将这些属性添加到所有组件吗?像这样:

<Button color="default" padding={10} margin={5}>

我知道使用纯 CSS 和类可以做到这一点,但我想使用 Material-UI 方式。

【问题讨论】:

    标签: reactjs material-ui customization


    【解决方案1】:

    您可以在 BOX 组件中使用 de "Spacing",只需先导入组件即可:

    import Box from '@material-ui/core/Box';
    

    Box 组件作为您想要“修改”间距的组件的“包装器”。

    然后你可以在组件上使用下一个属性:

    space 实用程序将速记边距和填充道具转换为边距和填充 CSS 声明。道具使用 {property}{sides} 格式命名。

    其中属性是以下之一:

    m - 用于设置边距的类 p - 用于设置填充的类

    其中边是以下之一:

    t - 用于设置 margin-top 或 padding-top 的类

    b - 用于设置 margin-bottom 或 padding-bottom 的类

    l - 用于设置 margin-left 或 padding-left 的类

    r - 用于设置 margin-right 或 padding-right 的类

    x - 对于同时设置 *-left 和 *-right 的类

    y - 对于同时设置 *-top 和 *-bottom 的类

    空白 - 用于在元素的所有 4 个边上设置边距或填充的类

    举个例子:

    <Box m={2} pt={3}>
      <Button color="default">
        Your Text
      </Button>
    </Box>
    

    【讨论】:

    • 对于那些对 m={2} pt={3} 感到困惑的人。这些基本上与主题中设置的间距有关。例如,如果您有像 const theme = { spacing: 8, } m ={2}set all margins to 8*2 pt={3} set padding top to 8*3 这样的主题
    • 这意味着多次使用Box 组件。这是如何推荐的?
    • @oskrgg:文档和其他各种资源说Box(没有任何component 装饰)是div 的简写。它尝试将每个提供的道具映射到其div 的相应CSS 属性。这通常有助于将此类道具保留在“代码”空间中,而不是强迫开发人员查找和更改样式、主题等。这个特别的答案让我觉得推荐和适当的使用。一般来说,Box 并不比添加div 差。
    • 我想知道为什么原作者 (@rostamiani) 没有接受这个作为答案。如果我正确理解了原始问题,那么这将回答它 - 它肯定对我有帮助,我来到这里是因为我认为我有与原始问题相同的需求。
    • @TomStambaugh 也许提问者想为Button 添加一个真正的填充。向Box 组件包装器添加填充就像向Button 添加边距一样。
    【解决方案2】:

    Material-UI 的样式解决方案以 JSS 为核心。它是一个高性能的 JS 到 CSS 编译器,可在运行时和服务器端运行。

    import { withStyles} from '@material-ui/core/styles';
    
    const styles = theme => ({
      buttonPadding: {    
        padding: '30px',   
      },
    });
    
    function MyButtonComponent(props) {
      const { classes } = props;
    
      return (      
          <Button
            variant="contained"
            color="primary"
            className={classes.buttonPadding}
          >
            My Button
          </Button>
      );
    }
    
    export default withStyles(styles)(MyButtonComponent);
    

    您可以使用 withStyle HOC 将样式注入到您的组件中。这就是它的工作原理,并且经过了非常优化。

    已编辑:要在所有组件中应用样式,您需要使用 createMuiTheme 并使用 MuiThemeprovider 包装您的组件

    const theme = createMuiTheme({
      overrides: {
        MuiButton: {
          root: {
            margin: "10px",
            padding: "10px"
          }
        }
      }
    });
    
     <MuiThemeProvider theme={theme}>
      <Button variant="contained" color="primary">
        Custom CSS
      </Button>
    
      <Button variant="contained" color="primary">
        MuiThemeProvider
      </Button>
    
      <Button variant="contained" color="primary">
        Bootstrap
      </Button>
    </MuiThemeProvider>
    

    【讨论】:

    • 是的,它适用于特定组件。但是如何为所有 MUI 组件声明这些道具?
    • 你可以为此创建MuiTheme并将你的组件包装在MuiThemeProvider中
    • 我不想为所有组件添加内边距和边距。我需要添加这些属性来为每个组件自定义它。
    • “我可以将这些属性添加到所有组件”这是您的问题陈述
    • MuiButton 引用从何而来?这是来自一些 MUI API 吗?为什么不Button
    【解决方案3】:

    在 Material-UI v5 中,可以使用 sx 属性更改按钮样式。您可以看到边距/填充系统属性及其等效的 CSS 属性here

    <Button sx={{ m: 2 }} variant="contained">
      margin
    </Button>
    <Button sx={{ p: 2 }} variant="contained">
      padding
    </Button>
    <Button sx={{ pt: 2 }} variant="contained">
      padding top
    </Button>
    <Button sx={{ px: 2 }} variant="contained">
      padding left, right
    </Button>
    <Button sx={{ my: 2 }} variant="contained">
      margin top, bottom
    </Button>
    

    mp 等属性简写是可选的,如果您想快速制作组件原型,如果您希望代码更具可读性,可以使用普通 CSS 属性。

    下面的代码与上面的代码相同,但使用了 CSS 属性:

    <Button sx={{ margin: 2 }} variant="contained">
      margin
    </Button>
    <Button sx={{ padding: 2 }} variant="contained">
      padding
    </Button>
    <Button sx={{ paddingTop: 2 }} variant="contained">
      padding top
    </Button>
    <Button sx={{ paddingLeft: 3, paddingRight: 3 }} variant="contained">
      padding left, right
    </Button>
    <Button sx={{ marginTop: 2, marginBottom: 2 }} variant="contained">
      margin top, bottom
    </Button>
    

    现场演示

    【讨论】:

      【解决方案4】:
      import Box from '@material-ui/core/Box';
      
      <Box m={1} p={2}>
        <Button color="default">
          Your Text
        </Button>
      </Box>
      

      【讨论】:

      • 请不要只发布代码作为答案,还要说明您的代码的作用以及它如何解决问题。带有解释的答案通常质量更高,更有可能吸引投票。
      【解决方案5】:

      在 4.0 版本之前,我们可以在 Typography 组件上使用 makeStyles 或样式属性来提供边距。

      我强烈建议使用 5.0 版的 Material ui,在这个版本上,Typography 有边距道具,它让生活变得轻松。

      【讨论】:

        【解决方案6】:

        我们可以使用material-ui的ma​​keStyles来实现这个不使用Box组件

        创建一个 customSpacing 函数,如下所示。

        customSpacing.js

        import { makeStyles } from "@material-ui/core";
        
        const spacingMap = {
          t: "Top", //marginTop
          b: "Bottom",//marginBottom
          l: "Left",//marginLeft
          r: "Right",//marginRight
          a: "", //margin (all around)
        };
        
        const Margin = (d, x) => {
          const useStyles = makeStyles(() => ({
            margin: () => {
              // margin in x-axis(left/right both)
              if (d === "x") {
                return {
                  marginLeft: `${x}px`,
                  marginRight: `${x}px`
                };
              }
              // margin in y-axis(top/bottom both)
              if (d === "y") {
                return {
                  marginTop: `${x}px`,
                  marginBottom: `${x}px`
                };
              }
              return { [`margin${spacingMap[d]}`]: `${x}px` };
            }
          }));
          const classes = useStyles();
          const { margin } = classes;
          return margin;
        };
        
        const Padding = (d, x) => {
          const useStyles = makeStyles(() => ({
            padding: () => {
              if (d === "x") {
                return {
                  paddingLeft: `${x}px`,
                  paddingRight: `${x}px`
                };
              }
              if (d === "y") {
                return {
                  paddingTop: `${x}px`,
                  paddingBottom: `${x}px`
                };
              }
              return { [`padding${spacingMap[d]}`]: `${x}px` };
            }
          }));
          const classes = useStyles();
          const { padding } = classes;
          return padding;
        };
        
        const customSpacing = () => {
          return {
            m: Margin,
            p: Padding
          };
        };
        
        export default customSpacing;

        现在将上面的 customSpacing 函数导入到您的组件中,并像下面这样使用它。 App.js

        import React from "react";
        import "./styles.css";
        import customSpacing from "./customSpacing";
        
        const App = () => {
          const { m, p } = customSpacing();
          return (
            <div className="App">
              <h1>Hello CodeSandbox</h1>
              <h2
                style={{ background: "red" }}
                className={`${m("x", 20)} ${p("x", 2)}`}
              >
                Start editing to see some magic happen!
              </h2>
            </div>
          );
        };
        
        export default App;

        click to open codesandbox

        【讨论】:

          【解决方案7】:

          特定于使用全局样式的“padding-top”(10px)

          Read this!

          import React from "react";
          import { Container, makeStyles, Typography } from "@material-ui/core";
          import { Home } from "@material-ui/icons";
          
          const useStyles = makeStyles((theme) => ({
          
          container: {
              paddingTop: theme.spacing(10),
          },
          }));
          
          const LeftBar = () => {
          const classes = useStyles();
          
          return (
              <Container className={classes.container}>
                  <div className={classes.item}>
                      <Home className={classes.icon} />
                      <Typography className={classes.text}>Homepage</Typography>
                  </div>
              </Container>
          );
          };
          
          export default LeftBar;
          

          【讨论】:

            【解决方案8】:

            首先在主题提供程序中设置初始间距,即包含您的应用程序条目的标签。它应该是这样的

            import { createMuiTheme } from '@material-ui/core/styles';
            import purple from '@material-ui/core/colors/purple';
            import green from '@material-ui/core/colors/green';
            
            const theme = createMuiTheme({
              palette: {
                primary: {
                  main: purple[500],
                },
                secondary: {
                  main: green[500],
                },
              },
            });
            function App() {
              return (
                  <ThemeProvider theme={theme}>
                    <LandingPage />
                  </ThemeProvider>
              );
             }
            

            就是这样。所以将主题部分添加到代码中并根据需要使用边距/填充

            const theme = {
              spacing: 8,
            }
            
            <Box m={-2} /> // margin: -16px;
            <Box m={0} /> // margin: 0px;
            <Box m={0.5} /> // margin: 4px;
            <Box m={2} /> // margin: 16px;
            

            您可以使用“margin”或“m”简称,同样适用于填充 或

            const theme = {
              spacing: value => value ** 2,
            }
            
            <Box m={0} /> // margin: 0px;
            <Box m={2} /> // margin: 4px;
            

            <Box m="2rem" /> // margin: 2rem;
            <Box mx="auto" /> // margin-left: auto; margin-right: auto
            

            【讨论】:

            • 如何为 留出边距
            • 这不能回答所提出的问题。 Box 组件默认具有 padding 和 margin 属性。这些问题询问如何将这些属性添加到其他组件(例如 Button)
            猜你喜欢
            • 2019-08-13
            • 1970-01-01
            • 1970-01-01
            • 2015-08-14
            • 1970-01-01
            • 2016-05-02
            • 1970-01-01
            • 1970-01-01
            • 2020-03-11
            相关资源
            最近更新 更多