【问题标题】:How to move global styles into a scope for emotion?如何将全球风格转移到情感的范围内?
【发布时间】:2020-06-19 09:01:36
【问题描述】:

我目前需要将库的常用组件集成到多个网站中。组件库当前具有全局样式。他们通过以下方式注入:

  <Global
    styles={`
        div {
          padding: 0;
        }
    `}
  />

我希望“全局样式”仅适用于该库的组件。它们仅在页面的一部分上。

所以我试试这个:

const Styles = styled.div`
        div {
          padding: 0;
        }
`;

const Page = () => (
    <Styles>
        <SomeComponentsOfTheLibrary />
    </Styles>
);

但似乎Styles 中的所有内容都具有优先权。那么如果组件有padding: 10px;,它将占用padding: 0; of Styles

这是转载的问题:

我知道这是一个 css 问题,但我想用情感来解决它

我已经看过了:

【问题讨论】:

标签: javascript css reactjs emotion


【解决方案1】:

如何将全局样式转移到情感范围内?

@Andarist 通过创建stylis plugin for extra scope 找到了解决方案

示例

使用 stylis 插件创建缓存以获得额外的范围

const STRONG_ID = 'very-strong-id';
const cache = createCache({
  stylisPlugins: [createExtraScopePlugin(`#${STRONG_ID}`)],
});

在缓存提供程序中使用您的全局样式

     <CacheProvider value={cache}>
        <Global
          styles={css`
            div {
              background-color: red;
            }
          `}
        />
        <div id={STRONG_ID}>
          <div>I must be red (global style scoped to the parent div)</div>
          <Container>
            I must be blue (local style defined on this div)
          </Container>
        </div>
      </CacheProvider>

那么你的全局样式将在very-strong-id范围内

你可以找到例子here

希望以后能对大家有所帮助?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-11
    • 2021-09-07
    • 1970-01-01
    • 2021-10-25
    • 2016-07-03
    • 2017-06-12
    • 2017-12-09
    • 1970-01-01
    相关资源
    最近更新 更多