【问题标题】:Styled component doesn't override inline styles样式化组件不会覆盖内联样式
【发布时间】:2021-08-02 02:18:26
【问题描述】:

我正在尝试覆盖第三方组件的内联样式。

我关注了文档how can i override inline styles

所以,我使用&[style] 覆盖了内联样式,但这不起作用。

我使用的第三方组件是CookieConsent

现在,我的组件看起来像这样:

import React from 'react';

import CookieConsent from 'react-cookie-consent';
import styled from 'styled-components';

const StyledCookieBanner = styled(CookieConsent)`
  &[style] {
    justify-content: center;
    align-items: center;
    width: calc(100% - 20px);
    margin: 10px;
    padding: 20px;
    background-color: white;
    border-radius: 22px;
    box-shadow: 0 0 19px 3px rgba(0, 0, 0, 0.17);
  }
`;

const CookieBanner = (): React.ReactElement => {
  return (
    <StyledCookieBanner debug buttonText='Ok'>
      Cookie
    </StyledCookieBanner>
  );
};

export default CookieBanner;

我也试过how can i override styles with higher specificity,但没有成功。

我发现覆盖样式的唯一方法是做类似的事情并使用!important

const StyledCookieBanner = styled(CookieConsent)`
  > div {
    justify-content: center;
    align-items: center !important;
    width: calc(100% - 20px) !important;
    margin: 10px;
    padding: 20px;
    background-color: white !important;
    border-radius: 22px;
    box-shadow: 0 0 19px 3px rgba(0, 0, 0, 0.17);
  }
`;

也试过了,没有成功

const StyledCookieBanner = styled(CookieConsent)`
  > div {
    // &&& {
    &[style] {
      justify-content: center;
      align-items: center;
      ...
    }
  }
`;

文档看起来很清楚,但我没有成功。

我错过了什么吗?这是可能的还是我应该使用style 组件道具?

【问题讨论】:

    标签: javascript css reactjs styled-components css-in-js


    【解决方案1】:

    从您链接的文档页面:

    内联样式始终优先于外部 CSS,因此您不能通过简单地增加特异性来覆盖它。

    让我们停在那里。 Styled Components 将 classes 添加到元素中。在 HTML/CSS 中,style 属性样式几乎总是胜过基于类的样式;没有任何样式组件(或任何其他基于类的库)可以改变这一点……除非您使用带有 !important 的“hack”,即……

    不过有一个巧妙的技巧,就是将 style element-attr CSS Selector 与 !important 结合使用:

    !important 是该 hack 的重要组成部分,因此您发布的(工作)代码:

    const StyledCookieBanner = styled(CookieConsent)`
     > div {
        justify-content: center;
        align-items: center !important;
        width: calc(100% - 20px) !important;
        margin: 10px;
        padding: 20px;
        background-color: white !important;
        border-radius: 22px;
        box-shadow: 0 0 19px 3px rgba(0, 0, 0, 0.17);
      }
    `;
    

    都是正确的,也是你唯一的选择。

    如果您真的想覆盖 style 属性...覆盖样式属性 :) 不要使用样式化组件,请在您的元素上使用 style 道具(或者在您的情况下,请 react-cookie-consent 采取一个style 道具来实现那个效果)。

    【讨论】:

      猜你喜欢
      • 2020-07-21
      • 1970-01-01
      • 2020-10-16
      • 2016-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-27
      • 2021-11-01
      相关资源
      最近更新 更多