styled-components全局样式为何晚于组件样式注入?如何调整顺序
问题1:GlobalStyle组件位置靠前但样式后注入的原因
styled-components的样式注入顺序和组件在React渲染树中的位置没有直接关联,底层逻辑区别如下:
- 普通
styled.xxx创建的组件样式,在代码解析阶段(组件定义完成时)就会提前注入到页面<head>的样式表中 createGlobalStyle创建的全局样式,需要等待对应的<GlobalStyle />组件实际挂载到DOM时才会触发注入
你的示例中StyledButton的定义早于<GlobalStyle />的挂载时机,所以它的样式先被注入,全局样式后注入,最终出现优先级倒置的问题。
问题2:调整注入顺序的解决方案
使用styled-components官方提供的StyleSheetManager组件,开启injectFirst配置即可,该配置会强制所有全局样式注入到所有普通组件样式的最前方,无需调整优先级。
修改后的入口代码示例如下:
import styled from "styled-components"; import { createGlobalStyle, StyleSheetManager } 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 ( <StyleSheetManager injectFirst> <GlobalStyle /> <MyComponent /> </StyleSheetManager> ); }
配置后页面<head>中的样式顺序会变为:
[type="submit"]{color:red;} .cshqdf{color:blue;}
同优先级下后定义的组件样式会覆盖全局样式,符合预期效果。
内容的提问来源于stack exchange,提问作者Giraphi
相关产品推荐
相关产品推荐

