Storybook中使用MUI组件页面空白的解决方法
Storybook中MUI组件渲染白屏解决方法
你遇到的白屏问题由3个常见错误导致,按以下步骤调整即可正常运行:
1. 修正React组件命名规范
React 强制要求自定义组件名必须以大写字母开头,你当前将组件命名为myButton(小写开头),JSX解析时会把它判定为原生Web组件,不会加载React组件逻辑,直接导致渲染失败。
修改对应代码:
// ./src/components/MyButton.js (文件名同步改为大写开头更符合规范) import * as React from 'react'; import Button from '@mui/material/Button'; // 组件名改为大写开头 export default function MyButton({ label }){ return( <Button variant="contained"> {label} </Button> ) }
// ./src/stories/MyButton.stories.js import MyButton from '../components/MyButton' export default { title: "Button", component: MyButton } const Template = (args) => <MyButton {...args} /> export const Primary = Template.bind({}); Primary.args = { label: "Press me" }
2. 给Storybook添加MUI全局主题装饰器
MUI组件运行依赖主题上下文,需要在Storybook全局配置中包裹ThemeProvider,否则组件无法获取主题配置会报错白屏。
修改Storybook预览配置文件.storybook/preview.js:
// .storybook/preview.js import React from 'react'; import { ThemeProvider, createTheme } from '@mui/material/styles'; import CssBaseline from '@mui/material/CssBaseline'; // 如需自定义MUI主题可在createTheme中传入配置 const muiTheme = createTheme(); export const decorators = [ (Story) => ( <ThemeProvider theme={muiTheme}> <CssBaseline /> <Story /> </ThemeProvider> ), ];
3. 确认安装MUI必需依赖
MUI v5默认以Emotion作为样式引擎,如果漏装相关依赖也会导致渲染失败,在项目根目录执行对应包管理器的安装命令:
# npm用户执行 npm install @mui/material @emotion/react @emotion/styled # yarn用户执行 yarn add @mui/material @emotion/react @emotion/styled
完成以上调整后重启Storybook服务,MUI组件即可正常渲染。
问题参考截图:
内容的提问来源于stack exchange,提问作者Miguel Leirosa
相关产品推荐
相关产品推荐


