【问题标题】:change Material UI Typography into styled-component将 Material UI Typography 更改为 styled-component
【发布时间】:2020-07-18 10:42:34
【问题描述】:

是否可以转换 Material UI 元素

<Container component="main" maxWidth="XS">
<Typography component="h1" variant="h5">
          Sign in
        </Typography>

进入样式化组件?

我试过这个排版,但文字看起来要小得多。

export const Typo = styled.h5`
export const Typo = styled(Typography)`
component: h1; 
variant: h5;
`

另一个例子:我尝试使用它,但mt: 8也不起作用。我也无法从 Material ui 系统导入 Box,所以在看到示例后尝试了此方法。

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

export const StyledBox = styled(Box)`
mt: 8;

【问题讨论】:

    标签: javascript reactjs typescript material-ui styled-components


    【解决方案1】:

    使用@material-ui/system

    @material-ui/system 提供称为“样式函数”的低级实用函数,用于构建强大的设计系统。

    与样式组件一起使用

    import styled from 'styled-components';
    import { palette, spacing, typography } from '@material-ui/system';
    
    const Box = styled.div`${palette}${spacing}${typography}`;
    

    对于排版

    在此处参考演示:https://material-ui.com/system/typography/#typography


    更新

    如果我们只想用styled-components为material-ui组件设置样式

    从普通 @material-ui/core 导入就可以了

    import { Typography } from '@material-ui/core';
    
    const StyledTyppgraphy = styled(Typography)`
      ...
    `;
    

    参考:样式组件文档Extending Styles

    【讨论】:

    • 我不太明白。这种排版的样式是否与普通 Material UI 核心排版的样式相同?那么我应该只在其中填写组件/变量值吗?我找不到任何这样的例子。另外,请查看更新后的 qs
    • 正如qs中提到的,我已经尝试过了,但它不能正常工作。即使我使用相同的样式属性,结果也会有所不同。也许我需要在 styled-component 中使用除变体和组件之外的其他东西
    【解决方案2】:

    正如@keikai 已经指出的,你可以extend styles

    我用几个例子做了一个Code Sandbox。 您可以只导入组件并像这样使用它:

    import { Typography } from "@material-ui/core";
    const StyledTypography = styled(Typography)``;
    
    <StyledTypography variant="h5" component="h1"></StyledTypography>
    

    如果不添加自定义样式,TypographyStyledTypography 应该看起来一样。

    Typography example(自定义颜色)

    import { Box } from "@material-ui/core";
    const StyledBox = styled(Box)``;
    
    <StyledBox mt={8}></StyledBox>
    

    Box example

    请注意,我包含了一种使用 Material UI 间距变量的可选方式。

    就像Material UI docs 中提到的那样,您还可以通过从@material-ui/system 导入spacing 来使用间距道具。这样你就可以在不扩展 Material UI 组件的情况下应用这些间距道具。 您也可以直接在样式组件中使用间距功能,但这超出了我认为的这个问题的范围。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-11
      • 2020-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-18
      • 2021-01-29
      • 2020-12-25
      相关资源
      最近更新 更多