我正在尝试覆盖第三方组件内联样式。
我遵循了文档 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
组件道具?
答案 0 :(得分:0)
从您链接的文档页面:
<块引用>内联样式始终优先于外部 CSS,因此您不能通过简单地增加特异性来覆盖它。
让我们就此打住吧。样式化组件向元素添加类。在 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
道具(或者在您的情况下,询问 { {1}} 使用 react-cookie-consent
道具来实现该效果)。