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

Material UI自定义Radio在FormControlLabel中触发SyntaxError报错

解决Material UI自定义Radio在FormControlLabel中使用的模块错误

问题分析

你遇到的Cannot use import statement outside a module错误,核心原因是自定义样式组件存在语法错误导致模块无法被正确解析,加上自定义Radio组件未转发必要props,共同触发了加载异常。

修复步骤

1. 修复Styled组件的语法错误

你的BpIcon组件定义中,箭头函数返回样式对象时未用括号包裹,JavaScript会将{}解析为函数体而非返回对象,直接导致语法错误。修改如下:

// ../../mui文件中的BpIcon定义
import { styled } from '@mui/material/styles';

export const BpIcon = styled('span')(({ theme }) => ({
  borderRadius: '50%',
  width: 16,
  height: 16,
  boxShadow:
    theme.palette.mode === 'dark'
      ? '0 0 0 1px rgb(16 22 26 / 40%)'
      : 'inset 0 0 0 1px rgba(16,22,26,.2), inset 0 -1px 0 rgba(16,22,26,.1)',
  backgroundColor: theme.palette.mode === 'dark' ? '#394b59' : '#f5f8fa',
  backgroundImage:
    theme.palette.mode === 'dark'
      ? 'linear-gradient(180deg,hsla(0,0%,100%,.05),hsla(0,0%,100%,0))'
      : 'linear-gradient(180deg,hsla(0,0%,100%,.8),hsla(0,0%,100%,0))',
  '.Mui-focusVisible &': {
    outline: '2px auto rgba(19,124,189,.6)',
    outlineOffset: 2,
  },
  'input:hover ~ &': {
    backgroundColor: theme.palette.mode === 'dark' ? '#30404d' : '#ebf1f5',
  },
  'input:disabled ~ &': {
    boxShadow: 'none',
    background:
      theme.palette.mode === 'dark' ? 'rgba(57,75,89,.5)' : 'rgba(206,217,224,.5)',
  },
}));

export const BpCheckedIcon = styled(BpIcon)({
  backgroundColor: '#137cbd',
  backgroundImage: 'linear-gradient(180deg,hsla(0,0%,100%,.1),hsla(0,0%,100%,0))',
  '&:before': {
    display: 'block',
    width: 16,
    height: 16,
    backgroundImage: 'radial-gradient(#fff,#fff 28%,transparent 32%)',
    content: '""',
  },
  'input:hover ~ &': {
    backgroundColor: '#106ba3',
  },
});

2. 转发FormControlLabel传递的Props给内部Radio

FormControlLabel会向control属性的组件传递checked、onChange等关键props,你的BpRadio组件需要将这些props转发给内部的Radio组件,否则无法实现正常的状态联动:

// 修改BpRadio组件
export const BpRadio = (props) => {
  return (
    <Radio
      disableRipple
      color="default"
      checkedIcon={<BpCheckedIcon />}
      icon={<BpIcon />}
      {...props} // 转发所有接收的props给内部Radio
    />
  )
}

3. 验证文件模块配置

确保自定义样式文件的扩展名是.jsx或.tsx(TypeScript项目),避免构建工具将其识别为CommonJS模块;同时确认文件内的导入语句均为ES模块格式(使用import而非require)。

验证修复

修改后重新运行项目,FormControlLabel配合自定义BpRadio组件即可正常工作,不会再出现模块导入错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 04:03:09