【问题标题】:Nesting components - applying independent styles嵌套组件 - 应用独立样式
【发布时间】:2019-02-16 01:22:15
【问题描述】:

所以我有一个反应组件,我可以将size prop 传递给它。它可以是 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>
  );
};

【问题讨论】:

  • 嗯,这应该是不可能的。因为每个都是完全不同的实体。您能否分享您的MyComponent 组件的代码?看看他的example:

标签: css reactjs sass


【解决方案1】:

交换样式包含的顺序。

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

在 CSS 中,如果项目具有相同的特性,则最后一个项目将优先。由于您的代码作为常规的子代码嵌套得很小,因此您的 CSS 也应该反映这一点。

【讨论】:

    【解决方案2】:

    您可以仅使用 css 手动完成,如下所示:

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

    或回退到内联样式:

    const small = {height : '40px'};
    const regular = {height : '60px'};
    const large = {height : '80px'};
    
    const Page = (props) => {
        return (
          <MyComponent style={regular}>
            {/* Some other HTML elements*/}
            <MyComponent style={small}>
              ...
            </MyComponent>
          </MyComponent>
        );
      };
    

    【讨论】:

      猜你喜欢
      • 2020-09-22
      • 2020-04-17
      • 2019-04-15
      • 2019-11-08
      • 2021-06-25
      • 2020-08-20
      • 1970-01-01
      • 2021-04-21
      • 1970-01-01
      相关资源
      最近更新 更多