Toggle Button 切换按钮
切换按钮组件可用于对相关选项进行分组。
为了强调组合之间的关联,每一组切换按钮应该共享一个容器。 当给定切换按钮的 value
属性时,ToggleButtonGroup
就可以控制其子按钮的选择状态(selected state)。
唯一的选择
在唯一的选择中,选择一个选项就会取消其他的选择状态。
In this example, text justification toggle buttons present options for left, center, right, and fully justified text (disabled), with only one item available for selection at a time.
Note: Exclusive selection does not enforce that a button must be active. For that effect see enforce value set. For that effect see enforce value set.
多选
Multiple selection allows for logically-grouped options, like bold, italic, and underline, to have multiple options selected.
<ToggleButtonGroup size="small" {...control}>
{children}
</ToggleButtonGroup>
<ToggleButtonGroup {...control}>{children}</ToggleButtonGroup>
<ToggleButtonGroup size="large" {...control}>
{children}
</ToggleButtonGroup>
<ToggleButtonGroup
color="primary"
value={alignment}
exclusive
onChange={handleChange}
>
<ToggleButton value="web">Web</ToggleButton>
<ToggleButton value="android">Android</ToggleButton>
<ToggleButton value="ios">iOS</ToggleButton>
</ToggleButtonGroup>
<ToggleButtonGroup
orientation="vertical"
value={view}
exclusive
onChange={handleChange}
>
<ToggleButton value="list" aria-label="list">
<ViewListIcon />
</ToggleButton>
<ToggleButton value="module" aria-label="module">
<ViewModuleIcon />
</ToggleButton>
<ToggleButton value="quilt" aria-label="quilt">
<ViewQuiltIcon />
</ToggleButton>
</ToggleButtonGroup>
强制设置值
If you want to enforce that at least one button must be active, you can adapt your handleChange function.
const handleAlignment = (event, newAlignment) => {
if (newAlignment !== null) {
setAlignment(newAlignment);
}
};
const handleDevices = (event, newDevices) => {
if (newDevices.length) {
setDevices(newDevices);
}
};
<ToggleButton
value="check"
selected={selected}
onChange={() => {
setSelected(!selected);
}}
>
<CheckIcon />
</ToggleButton>
自定义切换按钮
Here is an example of customizing the component. Here is an example of customizing the component. You can learn more about this in the overrides documentation page.
无障碍设计
ARIA
- ToggleButtonGroup 具有
role="group"
。 请您提供一个可访问的标签,标签包含aria-label="label"
,aria-labelledby="id"
或<label>
。 - ToggleButton 根据按钮的状态来设置
aria-pressed="<bool>"
。 您应该用aria-label
标记每个按钮。
键盘输入
At present, toggle buttons are in DOM order. Navigate between them with the tab key. The button behavior follows standard keyboard semantics. Navigate between them with the tab key. The button behavior follows standard keyboard semantics.