具有样式化组件的材料ui按钮

时间:2020-04-19 22:53:04

标签: javascript css reactjs typescript styled-components

我正在使用此材质的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

1 个答案:

答案 0 :(得分:1)

使用material-ui

时需要考虑一些事项
  1. You'll need to separate the style properties by semi-colons ;

  2. 即使如此,大多数样式仍被内置material-ui类覆盖,因为这些类具有更高的特异性。为了解决这个问题,请使用&&运算符在相同的特异性级别上应用样式。

  3. 最后,还需要在background上设置:hover才能覆盖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

中工作