You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Storybook中使用MUI 5 InputLabel的shrink布尔属性触发警告问题

问题描述

依赖版本:

  • mui: 5.2.7
  • @mui/styles: 5.2.5
  • @emotion/react: 11.7.1
  • @emotion/styled: 11.6.0
  • react: 17.0.2
  • storybook: 6.5.10

自定义MUI单选Select组件时,通过给InputLabel传入shrink属性实现标签收缩效果,该功能在项目及单元测试中表现正常,但在Storybook中触发以下警告:

react-dom.development.js:67 Warning: Received true for a non-boolean attribute shrink

同时标签未出现收缩效果,且在配置更简单的Codesandbox中无法复现该问题。

解决方案

1. 修正Storybook的Babel配置

Storybook可能未正确处理MUI的JSX转换,导致shrink布尔属性被误识别为字符串。在.storybook/main.js中添加Emotion的Babel插件:

module.exports = {
  babel: async (options) => {
    options.plugins.push('@emotion/babel-plugin');
    return options;
  },
};

2. 显式传递布尔类型的shrink属性

在Storybook环境中,属性传递可能存在类型转换问题,尝试用更明确的布尔值写法:

// 两种写法都可以,优先推荐简洁版
<InputLabel shrink />
// 或者
<InputLabel shrink={Boolean(yourCondition)} />

3. 完善Storybook的MUI主题装饰器

确保Storybook中正确注入MUI主题上下文,在.storybook/preview.js中添加:

import { ThemeProvider, createTheme } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';

const defaultTheme = createTheme();

export const decorators = [
  (Story) => (
    <ThemeProvider theme={defaultTheme}>
      <CssBaseline />
      <Story />
    </ThemeProvider>
  ),
];

4. 排查依赖兼容性问题

当前使用的Storybook 6.5.10和MUI 5.2.7可能存在版本兼容问题,可尝试:

  • 将Storybook升级到6.5.x系列的最新版本
  • 同步升级MUI及@emotion相关依赖到匹配的5.x新版本

5. 检查自定义组件的属性传递逻辑

确认自定义Select组件中,shrink属性未被其他逻辑意外转换为字符串类型,比如避免类似shrink={String(yourFlag)}的错误写法,确保传递的是原始布尔值。

内容的提问来源于stack exchange,提问作者kboul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 08:20:26