【问题标题】:How to render custom generated ruleset in styled-jsx如何在 styled-jsx 中呈现自定义生成的规则集
【发布时间】:2021-01-18 07:06:05
【问题描述】:

TL;DR

如何将包含一个或多个 CSS 规则的变量插入到 styled-jsx 中(在后台使用 styled-jsx-plugin-sass)?


我有以下 JSX 风格:

// src/pages/index.tsx
...
<style jsx>
  {`
    .test {
      height: 100vh;
      width: 100vw;
      background-color: green;
      ${contained}
     }
  `}
</style>

而contained 是一个变量,我试图将上述规则插入其中:

// src/styles/break.ts

export const contained = `
margin: 0 auto;
${breakAt("sm")(`
  width: calc(100% - 10vw);
`)}
${breakAt("md")(`
  width: calc(100% - 15vw);
`)}
@media screen and (min-width: calc(960px + 10vw)) {
  width: 960px;
}`;
...

注意事项:

breakAt是一个生成特定媒体查询的函数(breakpoint: string) =&gt; (content: string) =&gt; string

我已确保 styled-jsx-plugin-sass 配置正确 - 以原始方式编写生成的 CSS 符合预期。

我还研究了我认为 styled-jsx 的行为方式——它似乎对我在编写生成器((content: string) =&gt; string 作用于contained)并调用它时输入的代码进行了一些文字解析,并且解析器识别出我写了一个CallExpression,但因此未能呈现任何内容。

我知道这可以使用 @mixin/@include 来解决,但我正在挑选我目前喜欢的 Sass 功能(主要是嵌入式规则),并且很想知道有什么可能。

非常感谢您的输入和更正。 请在回答之前阅读完整的问题!

【问题讨论】:

    标签: javascript reactjs sass next.js styled-jsx


    【解决方案1】:

    我不是styled-components 的粉丝(还没有!),但在这种情况下似乎是有效的情况:

    import styled from "styled-components"
    // ... other imports
    
    const Wrapper = styled.div`
      /* ... scoped styles */
      ${contained} /* mixin */
    `
    
    export default SomeComponent({ children }) {
      return <Wrapper>This component was mixed in<Wrapper/>
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多