在React应用程序中实现主题

问题描述 投票:2回答:1

我的客户要求我们需要在反应应用程序中使用自定义主题。

用户可以选择其中一个可用的主题,这将改变一些css属性,如font-color,font-family等。

现在我使用className属性将css规则应用于我的应用程序。

我尝试了一些实现相同的方法,并找到了一种具有替代css的方法

<link rel="stylesheet"           href="main.css">
<link rel="stylesheet alternate" href="light.css" id="light" title="Light">
<link rel="stylesheet alternate" href="dark.css"  id="dark"  title="Dark">

<script>
function enableStylesheet (node) {
  node.rel = 'stylesheet';
}

function disableStylesheet (node) {
  node.rel = 'alternate stylesheet';
}
</script>

并根据用户选择切换rel值。

任何人都可以建议我实现相同的任何其他方式。

提前致谢。

css reactjs themes
1个回答
0
投票

您的使用是正确的实施方式。但是如果你有很多主题呢?加载所有css文件将妨碍网站。因此,我建议您更新源代码,而不是加载所有css文件并启用/禁用它们。

node.ref = 'dark.css';

这样,只有在使用时才需要css文件。一旦,文件正在被使用,下次它被缓存。所以以后再也不用担心了。显然,如果文件大小在初次使用时可能需要一些时间并且可能会影响性能。即使最好的事情是你不需要等待所有。


可是等等!!!

你正在使用反应。 React为我们提供了context api,我显然会在这种情况下使用它。这是一个摘录的例子:

import {ThemeContext, themes} from './theme-context';
import ThemeTogglerButton from './theme-toggler-button';

class App extends React.Component {
  constructor(props) {
    super(props);

    this.toggleTheme = () => {
      this.setState(state => ({
        theme:
          state.theme === themes.dark
            ? themes.light
            : themes.dark,
      }));
    };

    // State also contains the updater function so it will
    // be passed down into the context provider
    this.state = {
      theme: themes.light,
      toggleTheme: this.toggleTheme,
    };
  }

  render() {
    // The entire state is passed to the provider
    return (
      <ThemeContext.Provider value={this.state}>
        <Content />
      </ThemeContext.Provider>
    );
  }
}

function Content() {
  return (
    <div>
      <ThemeTogglerButton />
    </div>
  );
}

ReactDOM.render(<App />, document.root);

使用redux和记录器信息可以实现类似的概念,使我们的工作变得简单。

© www.soinside.com 2019 - 2024. All rights reserved.