React css样式管理,styled-components

93 阅读1分钟

前言

允许你在 JavaScript 文件中使用模板字符串语法定义样式,并将样式与组件紧密绑定在一起。你可以像编写普通的 CSS 样式一样编写样式,然后将其应用于组件。

主题色

在使用 styled-components 时,如果你想要获取全局的主题色(例如 SCSS 中设置的 $color-bgcd346),你可以使用 styled-components 提供的 ThemeProvider 和 withTheme 来实现。

首先,你需要创建一个主题(theme)对象,包含你在 SCSS 中设置的颜色值。然后,将这个主题对象传递给 ThemeProvider,这样所有使用 withTheme 包装的组件都可以访问主题中定义的属性。

例如:

import React from 'react';
import { ThemeProvider } from 'styled-components';
    
const theme = {
    colorBg: '#cd346'  // 替换为你在 SCSS 中设置的主题颜色
  };
function App() {
  return (
    <ThemeProvider theme={theme}>
      theme
    </ThemeProvider>
  );
}

现在,在任何使用 styled-components 的组件中,你都可以通过 props.theme 获取主题中定义的属性,通过extend可继承其它组件的样式。例如:

import styled from 'styled-components';
const StyledDiv.extend`
` = styled.div`
  background-color: ${props => props.theme.colorBg};
  z-index: ${p => p.zIndex}; // 接收组件传过来的参数
`;
// 继承StyledDiv的样式
const styledExtend = StyledDiv.extend`
    font-size: 13px;
`

function YourComponent(props) {
  return <StyledDiv zIndex="1"}>Content</StyledDiv>;
}

export default YourComponent;