嵌套组件-应用独立样式

时间:2019-02-15 15:33:11

标签: css reactjs sass

所以我有一个我可以传递size道具的react组件。可以是smallregularlarge并根据分配的css类的类型-它们看起来像这样:

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

问题在于,当我嵌套这些组件时(请参见下面的示例),我从父级那里获取样式(因此这里嵌套MyComponent的大小仍将是regular而不是{{1 }}-这是纯粹的CSS问题。

该如何解决,以便嵌套组件始终获得独立的样式?

small

2 个答案:

答案 0 :(得分:0)

交换包含样式的顺序。

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

在CSS中,如果各项具有相同的特异性,则最后一项优先。由于您的代码像普通孩子一样嵌套得很少,因此您的CSS也应该反映这一点。

答案 1 :(得分:0)

您可以仅使用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>
    );
  };
相关问题