我的“主要”组件中有以下 render
:
import ComponentA from './component-a.js';
import ComponentB from './component-b.js';
const App = React.createClass({
render: function() {
return (
<div>
<ComponentA/>
<ComponentB/>
</div>
);
}
});
ComponentA
需要一个 css
文件。所以我在 component-a.js
中有以下内容:
require ('./component-a.css');
const ComponentA = React.createClass({
render: function() {
return (
<div>component a</div>
);
}
});
… 而 ComponentB
没有。所以我在 component-b.js
中有以下内容:
const ComponentB = React.createClass({
render: function() {
return (
<div>component b</div>
);
}
});
ComponentA
所需的css
文件(仅)是:
div {
width: 100px;
height: 30px;
border: 1px solid red;
}
即使只有 ComponentA
需要 css
,ComponentB
也会受到影响。这是在浏览器中呈现的内容:
似乎页面中的所有div
元素都受到了ComponentA
所要求的样式的影响。这包括后续组件 ComponentB
的 div
(不需要 css
样式)以及div
包含 ComponentA
和 ComponentB
以及 React 添加的另一个 div
:
css
文件不是只影响需要它们的组件吗?如果不是,并且它们实际上是全局的,那么需要特定组件的css
文件的语义到底是什么?除了使用内联样式并将所有内容都放在 JS 代码中之外,是否有一种方法可以将 CSS 文件分隔开,以便它们只影响需要它们的 React 组件?如果要使用类名来实现这种效果,则无法保证当一个组件与其他组件一起使用时类名是唯一的。
最佳答案
CSS 仍然加载到浏览器中以影响整个页面。导入css文件只是为了将你的css和js一起模块化,这样当你充分利用你的模块加载器时,你不仅不会加载不必要的js,也不会加载不必要的css。
编辑:有关 Instagram 如何使用模块加载的视频:
https://www.youtube.com/watch?v=VkTCL6Nqm6Y&noredirect=1
您最好的解决方案仍然是为您的 css 命名空间。关于冲突问题,您可以使用比我在下面使用的更冗长的类名,例如 mjb-appname-componentname
让您的 ComonentA 渲染为:
render: function() {
return (
<div className="component-a">component a</div>
);
}
及其css文件是
.component-a div {
width: 100px;
height: 30px;
border: 1px solid red;
}
最好使用 css 预处理器,如 less
或 sass
.component-a {
div {
width: 100px;
height: 30px;
border: 1px solid red;
}
}
额外的:
关于 js 内联样式的有趣讨论:http://blog.vjeux.com/2014/javascript/react-css-in-js-nationjs.html
关于使用这种内联样式方法引发的问题的讨论:
关于css - React 组件中的 require css 也会影响其他组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40242182/