繁体   English   中英

CSS 被应用到所有文件,即使没有导入

[英]CSS getting applied to all files even though not imported

我正在处理 2 个组件: header.jsfooter.js

我也有 2 个 css 文件: header.module.cssfooter.module.css 他们都为a标签使用了不同的样式。

我在每个 js 文件中导入了相应的 CSS 文件,但是footer.module.cssa样式似乎超过了header.js中的样式,即使它没有被导入。

这是代码:

header.js

import React from "react"
import { Link } from "gatsby"
import "../styles/header.module.css";

const ListLink = props => (
  <li style={{display: `inline-block`, marginRight: `1rem`, fontSize: '1.15rem', fontWeight: 'bold'}}>
    <Link className="link" to={props.to}>{props.children}</Link>
  </li>
)

footer.js

import React from "react"
import "../styles/footer.module.css";

const FooterLink = props => (
  <li style={{ display: `inline-block`, marginRight: `1rem`, marginBottom:'0rem', fontSize: '1.05rem', fontWeight: 'bold'}}>
    <a href={props.to} target="_blank">{props.children}</a>
  </li>
)

header.module.css

a {
    color: var(--textLink);
    text-shadow: var(--textShadow);
    transition:.2s;
    background-image: var(--bgimage);
}

a:hover {
    color: #da1e11;
    background-image: none;
}

footer.module.css

a{
    color: var(--textLink);
    text-shadow: var(--textShadow);
    transition:.2s;
    background-image: none;
}

a:hover {
    color: #da1e11;
    background-image: none;
}

footerbackground-image属性超过了header中指定的属性。

根据文档,它import something from './something.module.css' ,然后<Component className={something.error}

如果您使用 Gatsby 的默认<Layout> ,它共享<Header><Footer>组件,因此,两者都在每个页面中加载每个 CSS ,如您在此处看到的:

  return (
    <>
      <Header siteTitle={data.site.siteMetadata.title} />
      <div>
        <main>{children}</main>
        <Footer>
          © {new Date().getFullYear()}, Built with
          {` `}
          <a href="https://www.gatsbyjs.org">Gatsby</a>
        </Footer>
      </div>
    </>
  )
}

最简单的解决方案是将每个组件包装在 class 中,以使 CSS 仅在 class 内部可用,如下所示:

import React from "react"
import { Link } from "gatsby"
import "../styles/header.module.css";

    const ListLink = props => (
      <li className="list__item">
        <Link className="link" to={props.to}>{props.children}</Link>
      </li>
    )

注意:例如,您甚至可以将<Link>包装在<div>中。

如果您使用 CSS 模块,我建议删除内联 styles 以避免混合 styles 并提高可读性。

<Footer>组件也是如此。

暂无
暂无

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

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