【问题标题】:material ui button with styled-components带有样式组件的材质 ui 按钮
【发布时间】:2020-08-02 09:07:34
【问题描述】:

我使用的是这个材质的 ui 按钮,它有一个紫色的背景

<Button
      component={Link}
      to={link}
      style={{
        background: '#6c74cc',
        borderRadius: 3,
        border: 0,
        color: 'white',
        height: 48,
        padding: '0 30px',
        width: 200,
      }}>

我尝试将其更改为样式组件:

export const StyledButton = styled(Button)`
  background: #6c74cc;
  border-radius: 3;
  border: 0;
  color: white;
  height: 48;
  padding: 0 30px;
  width: 200px;
`;

但它看起来完全不同。背景为白色,文本为黑色。即使我正在应用相同的样式。宽度也不同。我该如何解决这个问题?

https://codesandbox.io/s/condescending-frost-muv1s?file=/src/App.js

【问题讨论】:

    标签: javascript css reactjs typescript styled-components


    【解决方案1】:

    使用material-ui时有几点需要考虑

    1. You'll need to separate the style properties by semi-colons ;

    2. 即便如此,大多数样式都被内置的material-ui 类覆盖,因为这些类具有更高的特异性。要克服这个问题,请使用 &amp;&amp; 运算符将样式应用到相同的特异性级别。

    3. 最后,还需要在 :hover 上设置 background 以覆盖 material-ui 样式

    通过这些更改,您的样式组件将如下所示:

    export const StyledButton = styled(Button)`
      && {
        background: #6c74cc;
        border-radius: 3px;
        border: 0;
        color: white;
        height: 48px;
        padding: 0 30px;
        width: 200px;
        margin-right: 20px;
        &:hover {
          background: #6c74cc;
        }
      }
    `;
    

    你可以看到它在this CodeSandbox中工作

    【讨论】:

    • 我不认为这是唯一的问题。你能看到我添加的沙箱吗?很奇怪,但我的本地主机上的颜色与沙箱上的颜色不同,即使我从字面上复制了相同的部分。不过,宽度与我想要的不同(如
    • @a125 是的,还有更多事情要研究,看看我更新的答案和代码框链接
    猜你喜欢
    • 1970-01-01
    • 2020-05-20
    • 2018-10-08
    • 2019-10-19
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    相关资源
    最近更新 更多