更改主题,例如 Fabric Web(默认/深色)

Change theme like Fabric Web ( Default / Dark)

在fabric的文档页面,现在每个示例组件都有一个更改主题的功能 即:example enter image description here

我怎样才能实现这个功能。我有 2 个主题 (created in),我想在它们之间切换

这是我的首选方式,使用 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')
);

版主注意:很抱歉,这个答案原来是重复的。我删除了重复项。