Change theme like Fabric Web ( Default / Dark)

扶醉桌前 提交于 2020-05-28 06:07:06

问题


In the documentation page of fabric, now each example component have a change theme funcionality ie: example enter image description here

How can I achive this funcionality. I have 2 themes (created in) and I want to switch betwen thems


回答1:


Here is my preferred way, using React Context.

import React from 'react';
import { Fabric, Customizer } from '@fluentui/react';
import { useLocalStorage } from 'react-use';



// Setup Theme Context and create hooks

import {
  DefaultCustomizations,
  DarkCustomizations
} from '@uifabric/theme-samples';

export const ThemeList = {
  light: DefaultCustomizations,
  dark: DarkCustomizations
};

export const ThemeContext = React.createContext({
  theme: 'light',
  changeTheme: name => {}
});

const ThemeWrapper = ({ children }) => {
  return (
    <ThemeContext.Consumer>
      {({ theme }) => (
        <Customizer {...ThemeList[theme]}>
          <Fabric>{children}</Fabric>
        </Customizer>
      )}
    </ThemeContext.Consumer>
  );
};

export const ThemeProvider = ({ children }) => {
  const [theme, setTheme] = useLocalStorage('theme', 'dark');
  const changeTheme = name => ThemeList[name] && setTheme(name);
  const value = { theme, changeTheme };
  return (
    <ThemeContext.Provider value={value}>
      <ThemeWrapper>{children}</ThemeWrapper>
    </ThemeContext.Provider>
  );
};

export const useTheme = () => React.useContext(ThemeContext);



// Now demo how to use it


export function App() {
  const { theme, changeTheme } = useTheme();

  return (
    <button onClick={() => changeTheme('dark')}>
      Switch to dark
    </button>
  );
}

import ReactDOM from 'react-dom';

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

Note to moderator: Sorry that this answer was originally a duplicate. I deleted the duplicate.



来源:https://stackoverflow.com/questions/60214292/change-theme-like-fabric-web-default-dark

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!