在React中,如何防止组件的CSS导入应用于整个应用程序? [英] In React, how to prevent a component's CSS import from applying to the entire app?
问题描述
我正在为我的应用程序使用 facebook的create-react应用:
I'm using facebook's create-react app for my application:
在我的Login.js容器中,我这样导入CSS:
In my Login.js container, I am importing CSS like so:
import React from 'react';
import '../../styles/users/Login.css'
const Login = () => {
....
问题是将Login.css样式应用于我的整个应用程序...例如,如果Login.css具有:
The problem is the Login.css styles are being applied to my entire application... for example, if Login.css has:
body {
background:Red ;
}
整个应用程序的背景都是红色:甚至在Login容器之外。
The entire app would have a body of background: Red; Even outside of the Login container.
我期望/想要在容器内进行CSS导入仅适用于该特定容器。
What I expected/want is for a CSS import within a container to only apply to that particular container.
有可能w反应吗?开发人员应该如何应对容器特定的样式?我是否需要向所有容器添加ID并将其包含在整个CSS文件中?
Is that possible w React? How are react developers supposed to handle container specific stylings? Do I need to add an ID to all containers and include that in the entire CSS file?
推荐答案
1。解决方案:给您的DOM元素类名称以在CSS中使用它们。
JS:
1. Solution: Give your DOM elements class names to use them in your css.
JS:
// in Link.js
import React from 'react';
import '../../styles/Link.css'
const Link = ({children, href}) => (
<a className="link" href={href}>{children}</a>
);
CSS:
// Link.css
.link {
color: red;
}
2。解决方案:内联样式。
JS:
2. Solution: Inline styles.
JS:
// in Link.js
import React from 'react';
import '../../styles/Link.css'
const Link = ({children, href}) => (
<a style={color: 'red'} href={href}>{children}</a>
);
3。解决方案:JS中的CSS。
有些库试图解决样式问题:
3. Solution: CSS in JS.
There are some libraries that try to solve the styling issue:
观看此文章谈话: https://speakerdeck.com/vjeux/react-css-in-js
看看: https:/ /github.com/cssinjs
样式组件: https://github.com/styled-components/styled-components
这篇关于在React中,如何防止组件的CSS导入应用于整个应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!