【问题标题】:Using ThemeProvider in separate style sheets在单独的样式表中使用 ThemeProvider
【发布时间】:2021-12-30 22:12:42
【问题描述】:

我一直在尝试将样式组件中的 ThemeProvider 集成到现有项目中。但是在样式表中访问主题的项目时会遇到以下错误:

TypeError: Cannot read properties of undefined (reading 'sidebarImage')
  10 |     315deg,
  11 |     ${p => p.bgColor1} 0%,
  12 |     ${p => p.bgColor2} 74%),
> 13 |     url(${(props) => props.theme.images.sidebarImage});
     | ^  14 |     
  15 | background-size: cover;
  16 | background-repeat: no-repeat;

经过一番折腾,我找到了问题的根源。在我一直关注的tutorial 中,所有样式组件都定义在与使用它的组件相同的文件中(即 Container 定义在 App.js 中) .在我正在处理的项目中,所有样式组件都在单独的样式表中定义(因此 Container 将在 App.styles.js 中,然后导入到 App.js)。

将样式化的组件从 App.styles.js 移动到 App.js 解决了这个问题。但是,是否可以让样式表访问 Themeprovider?

【问题讨论】:

    标签: javascript reactjs styled-components themeprovider


    【解决方案1】:

    一旦我找到了问题的根源,就很容易解决。使用答案here 我已经制定了这个解决方案(尽管可能有更好的方法)。

    import { useTheme } from "styled-components";
    
    ...
    
    const Sidebar = (props) => {
        const theme = useTheme();
    
        ...
    
        return (
            <s.SidebarContainer theme={theme}
                                isSidebarOpen={isSidebarOpen}>
                
                <s.SidebarHeader theme={theme}>
                    {sidebarHeader}
                </s.SidebarHeader>
            </s.SidebarContainer>
        )
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-07
      • 2023-02-20
      • 1970-01-01
      • 2020-10-23
      • 1970-01-01
      • 1970-01-01
      • 2013-03-30
      相关资源
      最近更新 更多