一些加载到 React 应用程序的 CSS 未应用 [英] Some CSS loaded into React app are not applied

查看:22
本文介绍了一些加载到 React 应用程序的 CSS 未应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 React Static Boilerplate 构建一个 React 应用.

每个组件都有这样的目录结构:

MyComponent/-- MyComponent.css-- MyComponent.js-- 包.json

MyComponent.js 文件中,我正在做一个原始的 import './MyComponent.css'

假设我的 CSS 包含如下内容:

body { 背景色:橙色;}.card { 背景颜色:紫色;}

并且我组件中的渲染函数渲染一张卡片:

render() {返回 (<div className="card">Hello World</div>);}

页面主体会变成橙色,但卡片不会变成紫色.

为什么这个 css 没有完全应用于生成的 HTML?

解决方案

根据 React Static Boilerplate 网站,他们使用 CSS 模块 - 这可以解释为什么 body 标签受到尊重,但类选择器不是.

https://github.com/css-modules/css-modules

尝试像这样导入样式表:

从'./MyComponent.css'导入样式;

像这样在你的组件中使用它:

东西!

I'm building a react app with React Static Boilerplate.

Each component has a directory structure like this:

MyComponent/
-- MyComponent.css
-- MyComponent.js
-- package.json

and in the MyComponent.js file, I'm doing a raw import './MyComponent.css'

Let's say my CSS contains something like this:

body { background-color: orange; }
.card { background-color: purple; }

and the render function in my component renders a card:

render() {
  return (
    <div className="card">Hello World</div>
  );
}

The page's body will become orange, but the card will not become purple.

Why is this css not being fully applied to the HTML that is generated?

解决方案

According to the React Static Boilerplate website, they use CSS Modules - this would explain why the body tag is being respected but the class selector is not.

https://github.com/css-modules/css-modules

try importing the stylesheet like so:

import styles from './MyComponent.css';

The using it in your component like so:

<div className={styles.card}>something!</div>

这篇关于一些加载到 React 应用程序的 CSS 未应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆