0

我正在尝试在 Rebass 中使用主题,它建议使用 Theme UI 进行主题化。遵循以下指南后,我无法开始setColorMode编写我的故事书。

  1. 进口useColorMode
import React from 'react'
import { ColorMode, ThemeProvider, useColorMode } from 'theme-ui'
const ThemeWrapper = (props) => {
  const [colorMode, setColorMode] = useColorMode() // error
  //...
}

我收到此错误消息:[useColorMode] 需要 ThemeProvider 组件

  1. 进口useThemeUI
import { ColorMode, ThemeProvider, useThemeUI } from 'theme-ui'
const ThemeWrapper = (props) => {
  const context = useThemeUI()
  const { setColorMode } = context
  //...
}

后来,我有setColorMode 不是一个函数

context使用 进行检查console.log,它包含以下内容:

{
  components: Object { p: {…}, b: {…}, i: {…}, … }
  emotionVersion: "10.0.27"
  theme: null
}

useColorMode无处可寻。

我究竟做错了什么?


我当前的代码:

.storybook/config.js

import React, { useEffect } from 'react'
import addons from '@storybook/addons';
import { addDecorator, configure } from '@storybook/react';
import { ColorMode, ThemeProvider, useThemeUI } from 'theme-ui'
import theme from '../theme'

const channel = addons.getChannel();

const ThemeWrapper = (props) => {
  const context = useThemeUI()
  const { setColorMode } = context

  console.log(context)

  const setDarkMode = isDark => setColorMode(isDark ? 'dark' : 'default')

  useEffect(() => {
    channel.on('DARK_MODE', setDarkMode);
    return () => channel.removeListener('DARK_MODE', setDarkMode);
  }, [channel, setColorMode]);

  return (
    <ThemeProvider theme={theme}>
      <ColorMode/>
      {props.children}
    </ThemeProvider>
  );
}

addDecorator(renderStory => <ThemeWrapper>{renderStory()}</ThemeWrapper>);

configure([
  require.context('../components', true, /\.stories\.(jsx?|mdx)$/),
  require.context('../stories', true, /\.stories\.(jsx?|mdx)$/)
], module);

4

1 回答 1

3

我在这里问:https ://github.com/system-ui/theme-ui/issues/537我设法纠正了我有问题的代码。

该错误是由于useColorMode未在<ThemeProvider>.

我将配置文件更改为以下内容以缓解问题。它解决了我的问题。

import React, { useEffect } from 'react'
import addons from '@storybook/addons';
import { addDecorator, configure } from '@storybook/react';
import { ColorMode, ThemeProvider, useColorMode } from 'theme-ui'
import theme from '../theme'

const channel = addons.getChannel();

const ThemeChanger = () => {
  const [colorMode, setColorMode] = useColorMode();

  const setDarkMode = isDark => setColorMode(isDark ? 'dark' : 'default')

  useEffect(() => {
    channel.on('DARK_MODE', setDarkMode);
    return () => channel.removeListener('DARK_MODE', setDarkMode);
  }, [channel, setColorMode]);

  return <div/>
}

const ThemeWrapper = ({ children }) => {
  return (
    <ThemeProvider theme={theme}>
      <ThemeChanger/>
      <ColorMode/>
      {children}
    </ThemeProvider>
  );
}

addDecorator(renderStory => <ThemeWrapper>{renderStory()}</ThemeWrapper>);

configure([
  require.context('../components', true, /\.stories\.(jsx?|mdx)$/),
  require.context('../stories', true, /\.stories\.(jsx?|mdx)$/)
], module);

于 2020-01-02T17:30:48.147 回答