通过情感启用全局主题?

时间:2018-08-01 16:14:09

标签: javascript css reactjs styled-components emotion

我遵循了https://github.com/emotion-js/emotion/issues/546,其中情感的作者Kye提到了一个解决方案,尽管我并不完全理解。

因此,我制作了一个小型CodeSandBox来实现问题中提供的详细信息。如何在background-color中使injectGlobal主题起作用?

2 个答案:

答案 0 :(得分:1)

我找到了解决方案。完整的解决方案可以在https://codesandbox.io/s/r76p996zymhttps://github.com/deadcoder0904/emotion-global-theming

中找到

制作一个包含您的应用程序主题的theme.js文件

theme.js

export const theme = {
  LIGHT: {
    textColor: "black",
    bgColor: "white"
  },
  DARK: {
    textColor: "white",
    bgColor: "black"
  }
};

Global中包装withTheme组件,并且应该使用theme道具

Global.js

import React from "react";
import { injectGlobal } from "react-emotion";
import { withTheme } from "emotion-theming";

class Global extends React.Component {
  componentDidUpdate(prevProps) {
    if (this.props.theme.bgColor !== prevProps.theme.bgColor) {
      window.document.body.style.backgroundColor = this.props.theme.bgColor;
    }
    if (this.props.theme.textColor !== prevProps.theme.textColor) {
      window.document.body.style.color = this.props.theme.textColor;
    }
  }

  render() {
    injectGlobal`
      color: ${this.props.theme.textColor};
      background-color: ${this.props.theme.bgColor};
    `;
    return React.Children.only(this.props.children);
  }
}

export default withTheme(Global);

然后用App组件包装Global组件。由于Global组件需要theme,因此应将其包装在ThemeProvider

index.js

import React from "react";
import ReactDOM from "react-dom";
import { ThemeProvider } from "emotion-theming";

import Global from "./injectGlobal";
import { theme } from "./theme";

class App extends React.Component {
  state = {
    isLight: true,
    title: "Light Theme",
    theme: theme.LIGHT
  };

  _toggleTheme = () => {
    const { isLight } = this.state;
    const title = isLight ? "Dark Theme" : "Light Theme";
    const newTheme = isLight ? theme.DARK : theme.LIGHT;
    this.setState({
      isLight: !isLight,
      title,
      theme: newTheme
    });
  };

  render() {
    const { title, theme } = this.state;
    return (
      <ThemeProvider theme={theme}>
        <Global>
          <React.Fragment>
            <h1>{title}</h1>
            <button onClick={this._toggleTheme}>Toggle Theme</button>
          </React.Fragment>
        </Global>
      </ThemeProvider>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

注意-该答案仅在Emotion 10发行和API更改之前有效。如果Emotion版本小于10,请使用此解决方案。

答案 1 :(得分:1)

针对使用情感10的人们的更新:

import React from 'react'
import { withTheme, ThemeProvider } from 'emotion-theming'
import { css, Global } from '@emotion/core'

const makeGlobalStyles = theme => css`
  body {
    background: ${theme.bg};
  }
`

const GlobalStyles = withTheme(({ theme }) => (
  <Global styles={makeGlobalStyles(theme)} />
))


const App = () => (
  <ThemeProvider theme={{ bg: 'tomato' }}>
    <main>
      <h1>Hi</h1>
      <GlobalStyles />
    </main>
  </ThemeProvider>
)