css - 嵌套组件——应用独立样式

标签 css reactjs sass

所以我有一个 react 组件,我可以将 size 属性传递给它。它可以是 smallregularlarge 并且基于分配的 css 类类型 - 它们看起来像这样:

.my-component {
  &--small-size .column {
    height: 40px;
  }
  &--regular-size .column {
    height: 60px;
  }
  &--large-size .column {
    height: 80px;
  }
}

问题是,当我嵌套这些组件时(参见下面的示例),我从父级获取样式(因此这里嵌套的 MyComponent 的大小仍然是 regular 而不是 small - 这是纯 CSS 问题。

如何解决这个问题,使嵌套组件始终获得独立的样式?

const Page = (props) => {
  return (
    <MyComponent size="regular">
      {/* Some other HTML elements*/}
      <MyComponent size="small">
        ...
      </MyComponent>
    </MyComponent>
  );
};

最佳答案

交换样式包含的顺序。

.my-component {
  &--large-size .column {
      height: 80px;
  }
  &--regular-size .column {
      height: 60px;
  }
  &--small-size .column {
     height: 40px;
  }
}

在 CSS 中,如果元素具有相同的特异性,则最后一项优先。由于您的代码嵌套很小,就像常规子项一样,您的 CSS 也应该反射(reflect)这一点。

关于css - 嵌套组件——应用独立样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54712484/

相关文章:

css - 在循环中使用动态 SASS 函数名称

javascript - 助焊剂/助焊剂 : Updating routes based on state change

javascript - JS React 网站最好的无限滚动工具/组件?

html - (HTML & CSS) 仅主页上的透明导航栏。其他 View 中的黑色背景色

html - 为什么我的 CSS 有一个 8 像素的边框?

reactjs - 微前端、Web 组件和共享库

css - ionic 3 响应弹出窗口大小

jquery - 将 jQuery UI CSS 应用于 MVC .input-validation-error

javascript - HTML CSS - 不可拖动的图像和整洁的代码

block - CSS block 并排