Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Lemonreds opened this issue Sep 21, 2020 · 1 comment
Open

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

Lemonreds opened this issue Sep 21, 2020 · 1 comment

Comments

@Lemonreds
Copy link
Owner

原理

原理是通过切换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
Copy link
Owner Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant