在我的项目中,我使用了一些全局css变量,例如--space-unit,--header-height等。 它看起来像这样:
--space-unit: 10px;
--header-height: 70px;
@media (max-width: 991px) {
--space-unit: 7px;
--header-height: 40px;
}
@media (max-width: 991px) {
--space-unit: 5px;
}
对于不同的屏幕分辨率,变量是合适的。如何使用样式化组件实现此功能?也就是说,我创建了ThemeProvider,并在其中输入spaceUnit和headerHeight的初始值,但是以后如何动态更改它?
答案 0 :(得分:1)
您需要实现自己的主题更新方式,因为ThemeProvider不提供此功能。
您可以使用Context并将现有的ThemeProvider包装在包含更新程序功能的自己的提供程序中:
const ThemeContext = createContext();
const ThemeContextProvider = props => {
const [theme, setTheme] = useState(LIGHT_THEME);
return (
<ThemeContext.Provider value={{ setTheme, theme }}>
<ThemeProvider theme={theme}>
{props.children}
</ThemeProvider>
</ThemeContext.Provider>
)
}
然后在您的应用中:
const App = () => {
return (
<ThemeContextProvider>
<SomeComponent/>
</ThemeContextProvider>
)
}
const SomeComponent = props => {
const { setTheme, theme } = useContext(ThemeContextProvider);
return <div>hello there</div>
}