如何在Storybook中为styled-components应用全局样式?解决React未定义错误
问题分析与解决
出现ReferenceError: React is not defined的原因是你在代码里使用了JSX语法(包括<>短语法Fragment和<GlobalStyle />组件),但没有在preview.js中显式导入React。
虽然React 17+允许项目文件里不手动导入React就能写JSX,但Storybook的预览环境(尤其是旧版本)可能没配置自动注入React的支持,所以必须手动导入。
修复步骤
- 在
preview.js顶部添加React导入语句:
import React from 'react';
修改后的完整代码:
// preview.js import React from 'react'; import { getGlobalStyleSheet } from '../src/styles/globalStyle'; import { addDecorator, addParameters } from '@storybook/react'; import { createGlobalStyle } from 'styled-components'; addDecorator(story => { const styleSheet = getGlobalStyleSheet('light'); const GlobalStyle = createGlobalStyle` ${styleSheet}`; return ( <> <GlobalStyle /> {story()} </> ); });
- 如果你用的是Storybook 6.4+版本,也可以检查
.storybook/main.js的配置,确保framework设置为@storybook/react且相关依赖为最新版本,但最直接有效的解决方式还是手动导入React。
另外,你也可以把<>换成<React.Fragment>来临时规避,但显式导入React是更通用的方案,能避免后续其他JSX语法再出现同类问题。
内容的提问来源于stack exchange,提问作者London804
相关产品推荐
相关产品推荐

