代码之家  ›  专栏  ›  技术社区  ›  Abdul Rafay

反应-子组件样式表覆盖其他子组件的样式表

  •  1
  • Abdul Rafay  · 技术社区  · 7 年前

    我想分开申请 styleSheets 样式表 但由于样式被覆盖而无法实现。

    Stackblitz

    儿童.jsx:

    import React from 'react';
    import "./childa.css"
    
    export default () => <h1>Child A!</h1>;
    

    儿童.css:

    h1 {
      color: blue;
    }
    

    儿童b.jsx:

    import React from 'react';
    import "./childb.css"
    
    export default () => <h1>Child B!</h1>;
    

    儿童b.css:

    h1 {
      color: red;
    }
    

    样式表

    4 回复  |  直到 7 年前
        1
  •  2
  •   Bayek    7 年前

    css已经编写好了,所以我不能使用内联样式。有吗 这样我就不必重命名所有

    简短的回答:你现在还不能做到这一点。

    本文解释了所有不同的 ways to style react components . 在你的情况下,你能做的就是使用 css modules 将泛型类重命名为 h1 .h1 .

    查看这篇关于css模块的文章: Modular CSS with React

    注: css模块 在中不可用 create-react-app . 如果你一定要用的话,这里有一个 关于 how to use CSS Modules with create-react-app .

        2
  •  1
  •   axiedrella23    7 年前

    我认为这是由进口顺序引起的。 在父组件中

    import React from 'react'
    import ChildA from './ChildA'
    import ChildB from './ChildB'
    

    h1 规则将覆盖第一个

    应该为组件使用类,或者使用内联样式

        3
  •  0
  •   Mosè Raguzzini    7 年前

        4
  •  -1
  •   Seth Duncan    7 年前

    这可能不适用于整个应用程序,但我通过对元素(.childA和.childB)应用一个类来修复它。这就解决了问题。

    export default () => <h1 className='childB'>Child B!</h1>;