Javascript 材质UI:替代样式类

Javascript 材质UI:替代样式类,javascript,reactjs,material-ui,jsx,styled-components,Javascript,Reactjs,Material Ui,Jsx,Styled Components,我试着遵循这个原则,但是使用样式化的组件而不是JS。特别是,我无法采用前两种方法: 使用className 使用类 我已确保head中的注射顺序正确,因此这不是问题所在。我的问题是我需要的类没有添加到DOM中 另请注意:我设法使常规样式的组件与MUI配合良好。也就是说,以下工程可以罚款: import React from 'react'; import Button from '@material-ui/core/Button'; import Typography from '@materi

我试着遵循这个原则,但是使用样式化的组件而不是JS。特别是,我无法采用前两种方法:

  • 使用
    className
  • 使用
  • 我已确保head中的注射顺序正确,因此这不是问题所在。我的问题是我需要的类没有添加到DOM中

    另请注意:我设法使常规样式的组件与MUI配合良好。也就是说,以下工程可以罚款:

    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>
    
    但是,我希望将所有内容都保存在组件中

    因此,我的问题归结为:


    如何从组件内部向DOM添加本地范围的样式,而不使用样式化组件创建新的组件标记/变量?

    我将稍后查看这一点,看看是否可以提供帮助。不久前,我发现自己陷入了绝望的深渊,所以我可以表示同情。文档是很好的,但在涉及样式重写时,它只是不够清晰,特别是当有多种方法可以实现时。请在问题文本中提供您的MUI版本/您安装了哪些子目录?a、 e.
    /core
    /icons
    等。抱歉,我也很难让它正常工作。稍后我会再次尝试,我会关注这个问题,因为我很好奇现在的解决方案是什么。这里有一个沙盒模板,供其他有兴趣尝试回答的人使用:@zfrisch我认为如果您按照您所做的方式导入CSS样式表,它会工作得很好。因为CSS类随后被添加到DOM中。但是,我想知道是否有一种方法可以在组件本身中实现(不需要将MUI组件转换为样式化组件,或者像MUI文档中那样使用JSS HOC)。啊,我实际上并不是有意这么做的。我只是将您的依赖项加载到一个react模板中,该模板已经烘焙了该样式表,因此它并不是针对您的问题提供的解决方案。我不认为您链接到的指南旨在显示任何与您知道的已经起作用的内容不同的内容。它只是忽略了将结果设置为变量(或者导出结果以便可以导入到其他文件中使用)。我不认为它试图表明您可以通过这种方式覆盖默认的AppBar样式。
    styled(Typography)`
      &.my-class {
        margin-bottom: 5rem;
      }
    `;
    
    // In render:
    <Typography className="my-class" component="h2" variant="h2">
    
    // 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>