【发布时间】:2021-12-28 13:13:06
【问题描述】:
考虑这个使用 styled-components 的 react-app 示例:
import styled from "styled-components";
import { createGlobalStyle } from "styled-components";
import React from "react";
const GlobalStyle = createGlobalStyle`
[type="submit"] {
color: red;
}
`;
const StyledButton = styled.button`
color: blue;
`;
function MyComponent() {
return (
<>
<h1>My Component</h1>
<button type="submit">regular button</button>
<StyledButton type="submit">styled button</StyledButton>
</>
);
}
export default function App() {
return (
<>
<GlobalStyle />
<MyComponent />
</>
);
}
(见codesandbox)
我正在使用 [type="submit"] 为元素(按钮)设置全局样式,并希望稍后使用 StyledButton 覆盖该样式。
但 styled-components 似乎在组件样式之后注入全局样式,或者至少以这种方式打印它。如果我们使用浏览器开发工具检查输出的<head>,我们会发现:
.cshqdf{color:blue;}
[type="submit"]{color:red;}
这样,StyledButton 设置的蓝色被全局样式覆盖。 (这两个 css 选择器具有相同的优先级,因此依赖于顺序。我在示例中专门使用了这些选择器来说明问题。)
我的问题:
- 为什么没有在组件样式之前注入全局样式?我预计会出现这种情况,因为
<GlobalStyle/>在组件树中更高。 - 如何确保在组件样式之前注入我的全局样式,以便更轻松地覆盖它?
注意:
我完全知道有多种方法可以让StyledButton 应用它的样式,而不关心样式注入的顺序。一种可能性当然是:
const StyledButton = styled.button`
&& {
color: blue;
}
`;
但是,这样的解决方案不是我想要的。我正在尝试了解如何处理样式化组件的全局样式,以使具有相同优先级的选择器(用于组件)随后出现在样式表中,因此我不需要额外的技巧。
【问题讨论】: