css - React 组件中的 require css 也会影响其他组件

标签 css reactjs

我的“主要”组件中有以下 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 需要 cssComponentB 也会受到影响。这是在浏览器中呈现的内容:

enter image description here

似乎页面中的所有div元素都受到了ComponentA所要求的样式的影响。这包括后续组件 ComponentBdiv(需要 css 样式)以及div 包含 ComponentAComponentB 以及 React 添加的另一个 div:

enter image description here

  1. css 文件不是只影响需要它们的组件吗?如果不是,并且它们实际上是全局的,那么需要特定组件的 css 文件的语义到底是什么?

  2. 除了使用内联样式并将所有内容都放在 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 预处理器,如 lesssass

.component-a {
    div {
        width: 100px;
        height: 30px;
        border: 1px solid red;
    }
}

额外的:

关于 js 内联样式的有趣讨论:http://blog.vjeux.com/2014/javascript/react-css-in-js-nationjs.html

关于使用这种内联样式方法引发的问题的讨论:

https://github.com/callemall/material-ui/issues/4066

关于css - React 组件中的 require css 也会影响其他组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40242182/

相关文章:

jquery - 使用 jQuery.css 在 Internet Explorer 中获取值

javascript - javascript中的空格

css - 如何在不使用源按钮的情况下将类添加到 Umbraco 7 的 TinyMCE 中的表中?

reactjs - 如何在具有功能组件的 React 应用程序中使用 Google(通过 Firebase)登录用户?

reactjs - 将 font-awesome 添加到 React 项目时出错

reactjs - Redux 传奇 : What is the difference between using yield call() and async/await?

html - Bootstrap 不均匀列顺序

html - 具有响应高度的表格单元格的圆形边框形状

reactjs - Jest and react-router-dom : React. createElement : type is invalid -- expected a string (for built-in components) . .. 但得到:undefined

javascript - React 中的从右到左 (RTL) 支持