跳到主要内容

Css 变量方案

前言

Css 变量方案 基于 css-vars-ponyfill 实现换肤

实现


一、theme.tsx 管理主题状态

import cssVars from 'css-vars-ponyfill';

const theme = {
default: {
'--background--color': '#29CCCC',
},
light: {
'--background--color': '#fff',
},
dark: {
'--background--color': '#000',
},
};

const initTheme = (argu: 'default' | 'light' | 'dark') => {
document.documentElement.setAttribute('data-theme', argu || 'default');
cssVars({
watch: true,
variables: theme[argu],
onlyLegacy: false,
});
};

export default initTheme;

二、index.tsx 初始化主题

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import initTheme from './theme';

initTheme('default');

ReactDOM.createRoot(document.getElementById('app')!).render(<App />);

三、index.css 应用变量

.container {
width: 100px;
height: 100px;
background-color: var(--background--color);
}

四、通过事件切换主题

import React from 'react';
import './styles/index.css';
import initTheme from './theme';

function App() {
const changeTheme = (theme: 'default' | 'light' | 'dark') => {
initTheme(theme);
};
return (
<div className="container">
<button type="button" onClick={() => changeTheme('light')}>
改成白色
</button>
<button type="button" onClick={() => changeTheme('dark')}>
改成黑色
</button>
</div>
);
}

export default App;