代码之家  ›  专栏  ›  技术社区  ›  Magnus

材质UI:替代样式类

  •  1
  • Magnus  · 技术社区  · 6 年前

    MUI guide on overriding MUI styles ,但使用 样式化组件 而不是 JSS公司 . 尤其是,我无法获得前两种工作方法:

    1. 使用 className
    2. 使用 classes

    我已经确定注射顺序在头部是正确的,所以这不是问题。我的问题是我需要的类没有添加到DOM中。

    另请注意:我设法恢复正常 样式化组件 与…合作 . 即,以下工作正常:

    import React from 'react';
    import Button from '@material-ui/core/Button';
    import Typography from '@material-ui/core/Typography';
    import styled from 'styled-components';
    import { darken, fade } from '@material-ui/core/styles/colorManipulator';
    
    const StyledButton = styled(Button)`
      color: ${props => props.theme.palette.primary.contrastText };
      background: linear-gradient(45deg, #fe6b8b 30%, #ff8e53 90%);
      border-radius: ${props => props.theme.shape.borderRadius}px;
      height: 48px;
      padding: 0 30px;
      box-shadow: 0 3px 5px 2px rgba(255, 105, 135, 0.3);
      &:hover {
        background: ${props => {
          return `linear-gradient(45deg, ${darken(`#fe6b8b`, 0.2)} 30%, ${darken(`#ff8e53`, 0.2)} 90%)`;
        }};
      };
      font-size: 1.2rem;
      ${props => props.theme.breakpoints.up('md')} {
        font-size: 1rem;
      }
    `;
    
    // In render: 
    <StyledButton>Hello World</StyledButton>
    

    但是,以下操作不起作用:

    styled(Typography)`
      &.my-class {
        margin-bottom: 5rem;
      }
    `;
    
    // In render:
    <Typography className="my-class" component="h2" variant="h2">
    

    开发工具确实表明了这一点 my-class 确实添加了,但是,该类没有添加到DOM中。我跟着 this guide (第三种方法)。

    知道为什么吗?

    PS:我不想把排版变成一个StyledTyphography组件。我知道这是可行的(见上面的第一个例子)。相反,我想遵循MUI文档中的覆盖指南。

    相关安装包:

    • “@material ui/core”:“^3.9.3”
    • “styled components”:“^4.2.0”,

    如果我导入外部样式表,它就可以工作了:

    // style.css
    .my-class2 {
      margin-bottom: 3rem;
    }
    
    // index.js
    import React from 'react';
    import Typography from '@material-ui/core/Typography';
    import './style.css';
    
    const IndexPage = () => (
      <>
        <Typography className="my-class2" component="h2" variant="h2">
          Testing h2 (MUI)
        </Typography>
      </>
    );
    
    <Typography className="my-class2" component="h2" variant="h2">
      Testing h2 (MUI)
    </Typography>
    

    但是,我想把它都放在组件中。

    如何从组件内部将本地范围的样式添加到DOM中,而不创建新的组件标记/变量

    0 回复  |  直到 5 年前