简体   繁体   English

如何在 styled-jsx 中呈现自定义生成的规则集

[英]How to render custom generated ruleset in styled-jsx

TL;DR TL;博士

How does one insert a variable that contains one or more CSS rules into styled-jsx (using styled-jsx-plugin-sass under the hood)?如何将包含一个或多个 CSS 规则的变量插入到 styled-jsx 中(在后台使用 styled-jsx-plugin-sass)?


I have the following JSX style:我有以下 JSX 风格:

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

And contained is a variable that I'm trying to insert into it the mentioned rule:并且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;
}`;
...

Notes:笔记:

breakAt is a function that generates a specific media query (breakpoint: string) => (content: string) => string breakAt是一个 function 生成特定媒体查询(breakpoint: string) => (content: string) => string

I have ensured that styled-jsx-plugin-sass is configured correctly - writing the generated CSS in raw acts as intended.我已确保正确配置了styled-jsx-plugin-sass - 按预期编写生成的 CSS 原始行为。

I've also looked into how I believe styled-jsx behaves - it seems to do some literal parsing of the code I put in as I wrote a generator ( (content: string) => string acting on contained ) and called it, and the parser recognised that I wrote a CallExpression , but failed to render anything because of that.我还研究了我认为 styled-jsx 的行为方式 - 它似乎对我在编写生成器( (content: string) => string作用于contained的)并调用它时输入的代码进行了一些文字解析,并且解析器认识到我写了一个CallExpression ,但没有因此而渲染任何东西。

I understand that this could be solved using @mixin/@include but I'm picking and choosing features of Sass that I like at this point (mainly embedded rules), and was curious to see what was possible.我知道这可以使用@mixin/@include来解决,但我正在挑选我喜欢的 Sass 的功能(主要是嵌入式规则),并且很想知道有什么可能。

Your input and correction is greatly appreciated.非常感谢您的输入和更正。 Please read the full question before answering!请在回答之前阅读完整的问题!

I'm not a fan of styled-components (yet:) but it seems to be the valid situation in this scenario:我不是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/>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM