styled-components的使用

216 阅读1分钟

styled-components 是一个 React 库,用于使用 JavaScript 编写 CSS 样式。嵌套规则在 styled-components 中与传统的 CSS 或 SASS 非常相似。嵌套样式可以使你根据组件的层次结构管理样式。

styled-components 中使用嵌套的基本规则是:

import styled from 'styled-components';

const Wrapper = styled.div`
  color: white;
  /* 嵌套规则:在Wrapper组件下的p元素将应用这些样式 */
  p {
    font-size: 20px;
  }
`;

// 使用
<Wrapper>
  <p>Hello, world!</p>
</Wrapper>

在这个例子中,Wrapper 组件内的所有 p 元素都将应用样式 font-size: 20px;。注意,这些样式仅应用于该组件的范围内,而不是全局。

你还可以使用 & 选择符来引用父级元素。例如:

import styled from 'styled-components';

const Button = styled.button`
  color: white;
  background: black;

  /* 当鼠标悬停在Button上时,应用这些样式 */
  &:hover {
    background: grey;
  }
`;

// 使用
<Button>Hover me!</Button>

在这个例子中,当鼠标悬停在 Button 上时,它的背景颜色会变成灰色。& 符号代表父级元素,也就是当前 Button 组件。

以上就是 styled-components 中的基本嵌套规则。在实践中,根据需要选择适当的嵌套级别和复杂性。注意,过度嵌套可能会导致样式难以理解和管理,因此,最好保持尽可能简单和明了。