Lemonreds / snippets

code snippets.
https://github.com/Lemonreds/snippets/issues
2 stars 0 forks source link

[2020-09-21]: 通过var()实现主题换肤。 #16

Open Lemonreds opened 4 years ago

Lemonreds commented 4 years ago

原理

原理是通过切换css变量,在组件样式中使用var(),会相应改变,换肤则通过更改顶层元素的类名来切换当前的css变量。

1. 先配置好主题色

  .theme-normal {
    --primary: #d23669;
    --bg: #fff;
    --nav: #4d5164;

    --block-bg: #e4edf7;
    --text-front: #242425;
  }

  .theme-dark {
    --primary: #d23669;
    --bg: #282c35;
    --nav: #fff;

    --block-bg: #e6e6e6;
    --text-front: rgba(255, 255, 255, 0.88);
  }

2. 在组件元素中使用css变量

.footer {
  color: var(--bg);
}

3.在body元素(或者其他顶层元素,<div id='root')增加css类名,.theme-dark/normal。

react例子:

import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'dva';
import Swtich from 'components/Form/Switch';
import { Themes } from 'models/theme';
import styles from './Themes.less';

function ThemesComponent({ theme, dispatch }) {
  const [value, set] = useState(theme === Themes.DARK);
  const onChange = v => {
    set(v);
    dispatch({
      type: 'theme/changeTheme',
      payload: { theme: v ? Themes.DARK : Themes.NORMAL },
    });
  };

  return ReactDOM.createPortal(
    <div className={styles.root}>
      <Swtich value={value} onChange={onChange} />
    </div>,
    document.getElementById('root'),
  );
}

export default connect(store => ({
  theme: store.theme.theme,
}))(React.memo(ThemesComponent));
Lemonreds commented 4 years ago

demo:https://lemonreds.github.io/react-components/