【问题标题】:Dynamically add styles to styled-jsx in Next.js在 Next.js 中为 styled-jsx 动态添加样式
【发布时间】:2019-07-21 21:05:43
【问题描述】:

请查看代码。我想有条件地为 about 链接添加一些额外的样式,所以我将它添加到标签的模板字符串的 ${} 中。这不会应用新样式。

我尝试过连接模板字符串。那也没用。

我无法在标签中设置 style={style},因为那样我将无法使用 :hover 样式。

import Link from 'next/link'
import { withRouter } from 'next/router'

const Header = ({ children, router, href }) => {
  const isIndex = router.pathname === "/";
  const isAbout = router.pathname === "/about";
  return (
    <div>
        <Link href="/">
          <a id="home">Timers</a>
        </Link>
        <Link href="/about">
          <a id="about">About</a>
        </Link>
        <style jsx>{
          `
            a {
              font-family: 'Montserrat Subrayada', sans-serif;
              color: #ffffff;
              text-decoration: none;
              font-size: 24px;
              padding: 2px;
              margin-right: 30px;
            }
            a:hover {
              color: #000000;
              background-color: #ffffff;
              border-radius: 2px;
            }
            ${isAbout ? `
            #about {
              background-color: red;
              color: #000000;
            }
            #about:hover {
              background-color: blue;
              color: #ffffff;
            }
            ` : ``}

          `
        }</style>
    </div>
)}

export default withRouter(Header)

如何应用条件样式?

【问题讨论】:

    标签: javascript reactjs jsx next.js


    【解决方案1】:

    由于 styled-jsx 在构建时编译样式,它无法预处理动态样式,这是 docshere 中提到的限制

    插件可以使用流行的预处理器,如 SASS、Less、Stylus、PostCSS,或在编译时对样式应用自定义转换。

    【讨论】:

      【解决方案2】:

      解决方案是仅动态更改属性值,而不是在单个条件中添加全新的选择器,您必须为每个属性执行此操作,如下所示:

      <style jsx>{
        `
          a {
            font-family: 'Montserrat Subrayada', sans-serif;
            color: #ffffff;
            text-decoration: none;
            font-size: 24px;
            padding: 2px;
            margin-right: 30px;
            border-radius: 2px;
          }
          a:hover {
            color: #000000;
            background-color: #ffffff;
          }
          #home {
            background-color: ${isHome ? "#ffffff" : ""};
            color: ${isHome ? "#000000" : ""};
          }
          #about {
            background-color: ${isAbout ? "#ffffff" : ""};
            color: ${isAbout ? "#000000" : ""};
          }
        `
      }</style>
      

      (我在提问的时候想出了问题的答案,所以我想我还是把它和我的答案一起发布,以防其他人需要它)

      【讨论】:

      • 使用 styled-components 代替,它更灵活,允许您编写问题中的样式。
      猜你喜欢
      • 2020-08-19
      • 1970-01-01
      • 2020-05-13
      • 1970-01-01
      • 2020-12-26
      • 2018-03-01
      • 2018-10-20
      • 2021-11-04
      • 2020-04-20
      相关资源
      最近更新 更多