【React】styled-components 基本使用-主题使用

时间:2024-11-06 16:41:14

theme.ts

const theme = {
  color: {
    primary: '#c20c0c',
    secondary: ''
  },
  size: {},
  mixin: {
    wrapv1: `
      width: 1100px;
      margin: 0 auto;
    `,
    textNowrap: `
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;`
  }
}

export default theme

index.tsx

import React from "react";
import ReactDOM from "react-dom/client";
import App from "@/App";
import "normalize.css";
// 导入全局样式
import "./assets/css/index.scss";
import { HashRouter } from "react-router-dom";
import store from "@/store";
import { Provider } from "react-redux";
import { ThemeProvider } from "styled-components";
import theme from "@/assets/theme";

const root = ReactDOM.createRoot(
  document.getElementById("root") as HTMLElement
);
root.render(
  <React.StrictMode>
    <Provider store={store}>
      <ThemeProvider theme={theme}>
        <HashRouter>
          <App />
        </HashRouter>
      </ThemeProvider>
    </Provider>
  </React.StrictMode>
);

在 styled-components 组件中直接使用 :

background-color: ${(props) => props.theme.color.primary};