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

如何在Material-UI Switch组件标签中添加星号?

问题解决:FormControlLabel设置required后星号不显示

你遇到的问题是因为FormControlLabel的required属性不会自动渲染必填星号——这个属性只是把必填状态传递给内部的表单控件(比如你用的Switch),但Material-UI的必填星号是由FormControl组件来统一处理的。

两种解决方法

方法一:用FormControl包裹(推荐,符合组件规范)

把FormControlLabel放在FormControl组件内部,将required属性移到FormControl上,这样组件会自动为标签添加星号:

import { FormControl, FormControlLabel, Switch } from '@mui/material';

// ...你的其他代码

<FormControl 
  required={row.formDesc.name.is_mandatory === 'Y'}
  error={hasError('name')}
>
  <FormControlLabel
    control={
      <Switch
        onChange={event =>
          onChangeRow(
            rowIndex,
            'name',
            event.target.checked === true ? 'Y' : 'N'
          )
        }
        disableRipple
        style={{ backgroundColor: 'transparent' }}
        checked={row.address.name === 'Y'}
        color='primary'
      />
    }
    labelPlacement='start'
    label={'Name?'}
    disabled={issubmited.value ? disabled : row.formDesc.name.is_editable === 'N'}
    helperText={getError('name')} // 注意原代码的helpertext是拼写错误,应为驼峰helperText
  />
</FormControl>

方法二:手动添加星号

如果不想用FormControl包裹,可以直接在label文本里拼接星号,适合简单场景:

<FormControlLabel
  // ...其他属性不变
  label={row.formDesc.name.is_mandatory === 'Y' ? 'Name? *' : 'Name?'}
/>

额外注意

原代码里的helpertext是拼写错误,Material-UI的属性是驼峰式的helperText,修正后才能正确显示错误提示文本。

内容的提问来源于stack exchange,提问作者KARTHIKEYAN.A

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 22:42:10