样式组件仅将样式应用于嵌套选择器

时间:2019-12-26 21:31:51

标签: reactjs sass styled-components

我希望所有文本的权重为800,包括一个className为txt-rotate的跨度。此外,子跨度将被着色并加下划线。为此,我使用了以下样式化的组件定义:

export const Slider = styled.h2`
  font-weight: 800;
  .txt-rotate {
    color: ${(props) => props.theme.primaryColor};
    text-decoration: underline;
  }
`;

然后这是我使用组件的时间:

<Slider>I'm a&nbsp;
    <span className="txt-rotate" 
          data-period={2000} 
          data-rotate='[ "Hacker.", "Coder.", "Maker.", "Entrepreneur." ]' />
</Slider>

跨度的文本最终以primaryColor结尾,并且带下划线,但是没有对所有文本进行加权。在检查器中,我看到没有任何样式应用于滑块的div,除了其中的范围。

更新: 我通过重新排序样式化组件的导出来解决问题。样式组件Slider位于底部,现在用作倒数第二个样式组件定义。为什么会这样?

1 个答案:

答案 0 :(得分:1)

  

要使用400或700以外的值查看效果,所使用的字体必须具有与指定的权重匹配的内置字体。

请参阅https://css-tricks.com/almanac/properties/f/font-weight/

const Slider = window.styled.h2`
  font-weight: ${props => props.weight};
  background: ${props => props.background};
  .txt-rotate {
    text-decoration: underline;
  }
`;
const App = () => (
 <div>
  <Slider weight="100" background="grey">
    One <span className="txt-rotate">I am a span (100)</span>
  </Slider>
  <Slider weight="200" background="green">
    Two <span className="txt-rotate">I am a span (200)</span>
  </Slider>
  <Slider weight="300" background="cyan">
    Three <span className="txt-rotate">I am a span (300)</span>
  </Slider>
  <Slider weight="400">
    Four <span className="txt-rotate">I am a span (400)</span>
  </Slider>
  <Slider weight="500">
    Five <span className="txt-rotate">I am a span (500)</span>
  </Slider>
  <Slider weight="600">
    Six <span className="txt-rotate">I am a span (600)</span>
  </Slider>
  <Slider weight="700">
    Seven <span className="txt-rotate">I am a span (700)</span>
  </Slider>
  <Slider weight="800">
    Eight <span className="txt-rotate">I am a span (800)</span>
  </Slider>
  <Slider weight="900">
    Nine <span className="txt-rotate">I am a span (900)</span>
  </Slider>
  </div>
);

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/styled-components/4.4.1/styled-components.min.js"></script>

<div id="root"></div>