Switch 开关组件
开关控制能切换单个设置的开/关两个状态。
开关组件是在移动设备上调整设置的首选方式。 The option that the switch controls, as well as the state it's in, should be made clear from the corresponding inline label.
<Switch {...label} defaultChecked />
<Switch {...label} />
<Switch {...label} disabled defaultChecked />
<Switch {...label} disabled />
<FormGroup>
<FormControlLabel control={<Switch defaultChecked />} label="Label" />
<FormControlLabel disabled control={<Switch />} label="Disabled" />
</FormGroup>
<Switch {...label} defaultChecked size="small" />
<Switch {...label} defaultChecked />
<Switch {...label} defaultChecked />
<Switch {...label} defaultChecked color="secondary" />
<Switch {...label} defaultChecked color="warning" />
<Switch {...label} defaultChecked color="default" />
<GreenSwitch {...label} defaultChecked />
<Switch
checked={checked}
onChange={handleChange}
inputProps={{ 'aria-label': 'controlled' }}
/>
带有 FormGroup 的开关
FormGroup
is a helpful wrapper used to group selection controls components that provides an easier API. FormGroup
is a helpful wrapper used to group selection controls components that provides an easier API. However, you are encouraged to use Checkboxes instead if multiple related controls are required. (参见: 何时使用)。 (参见: 何时使用)。
自定义样式开关
你可以参考以下一些例子来自定义组件。 您可以在 重写文档页面 中了解更多有关此内容的信息。
Off
On
🎨 If you are looking for inspiration, you can check MUI Treasury's customization examples.
标签放置
The switch also comes with an unstyled version. It's ideal for doing heavy customizations and minimizing bundle size. It's ideal for doing heavy customizations and minimizing bundle size.
何时使用
Accessibility
- 它将渲染一个带有
checkbox
而不是switch
角色的元素,鉴于该属性尚未得到广泛支持。 请首先测试目标受众的辅助技术 (assistive technology) 是否正确支持此 role 属性。 或者您可以使用<Switch inputProps={{ role: 'switch' }}>
来更改 role 属性。 - 所有表单控件都应该带有标签,而这包括了单选按钮,复选框和开关。 在大多数情况下,这是通过使用一个
<label>
元素(FormControlLabel)实现的。 - 如果无法使用标签,您则必须在输入组件中直接添加属性。 在这种情况下,您可以通过
inputProps
属性来应用附加的属性(例如aria-label
,aria-labelledby
,title
)。
<Switch value="checkedA" inputProps={{ 'aria-label': 'Switch A' }} />
Unstyled
The component also comes with an unstyled version. It's ideal for doing heavy customizations and minimizing bundle size.