【问题标题】:How to fix scss styles leaking across pages?如何修复跨页面泄漏的 scss 样式?
【发布时间】:2020-02-20 23:04:28
【问题描述】:

我有一个包含以下文件的项目:

/* styles/1.scss */
body {
  /* Some other stuff not related to background-color */
}
/* styles/2.scss */
body {
  background-color: blue;
}
// pages/one.js
import "../styles/1.scss";

export default ()=>(
  <div>Hello, One!</div>
)

访问localhost:3000/one 时,我注意到背景是蓝色的,尽管background-color 从未在1.scss 中设置样式!

我相信这与 css 模块有关,所以我尝试用 :local 包装 2.scss。 另外,我尝试将2.scss 重命名为2.module.scss,但无济于事。

我该如何解决这个问题?感谢您的帮助!

编辑: 在代码沙箱上查看此问题:https://codesandbox.io/s/priceless-flower-oswh1

如果背景不是橙色的,点击“转到二”然后回到一,橙色的身体会一直存在。

【问题讨论】:

  • 尝试重命名为_2.scss
  • 你确定你没有在任何地方导入 2.scss。因为 if 是在其他正在使用文件的地方导入的。它会生效。

标签: javascript css next.js


【解决方案1】:

您需要一些全局样式来设置 body 元素的样式或提供 css 重置。

选项 1:

// one.js
import Link from "next/link";

export default () => (
  <div>

    <style jsx global>{`
      body {
        background-color: red;
      }
    `}</style>

    Hello, One!
    <Link href="/two">
      <a>Go to two</a>
    </Link>
  </div>
);

// two.js
import Link from "next/link";

export default () => (
  <div>

    <style jsx global>{`
      body {
        background-color: orange;
      }
    `}</style>

    Hello, Two!
    <Link href="/one">
      <a>Go to one</a>
    </Link>
  </div>
);

您也可以将样式保存在单独的文件中,然后将其导入您需要的地方。

选项 2:

// styles/one_style.js
import css from "styled-jsx/css";

export default css.global`
  body {
    background-color: red;
  }
`;

// one.js
import globalStyles from "../styles/one_style";
import Link from "next/link";

export default () => (
  <div>

    <style jsx global>
      {globalStyles}
    </style>

    Hello, One!
    <Link href="/two">
      <a>Go to two</a>
    </Link>
  </div>
);

Code Sandbox

我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    • 2020-01-31
    • 2018-05-09
    • 2018-07-12
    相关资源
    最近更新 更多