切换
Switch 组件用于表示 checked 与 not checked 状态之间的切换。
安装
The above command is for individual installation only. You may skip this step if @heroui/react is already installed globally.
导入
用法
带标签
禁用
尺寸
颜色
带滑块图标
带图标
你也可以通过使用 startContent 和 endContent 属性在开关的开始和结束添加图标。
受控
注意: HeroUI Switch 也支持原生事件,如
onChange,可用于诸如 Formik 和 React Hook Form 等表单库。
插槽
- base:切换的基准插槽。它是主要包装器。
- wrapper:开始图标、结束图标和滑块的包装器。
- hiddenInput:用于处理开关状态的隐藏输入元素。
- thumb:开关的滑块元素。它是圆形元素。
- label:切换的标签插槽。
- startContent:开关起始位置的图标插槽。
- endContent:开关结束位置的图标插槽。
- thumbIcon:滑块内部的图标插槽。
自定义样式
自定义实现
In case you need to customize the switch even further, you can use the useSwitch hook to create your own implementation.
数据属性
Switch has the following attributes on the base element:
- data-selected:当开关处于选中状态时。基于
isSelected属性。 - data-pressed:当开关被按压时。基于 usePress
- data-readonly:当开关为只读时。基于
isReadOnly属性。 - data-hover:当鼠标悬停在开关上时。基于 useHover
- data-focus:当开关获取焦点时。基于 useFocusRing.
- data-focus-visible:当开关通过键盘获取焦点时。基于 useFocusRing.
- data-disabled:当开关被禁用时。基于
isDisabled属性。
可访问性
- 使用原生 HTML
<input>元素构建。 - 完全支持浏览器功能,如表单自动填充。
- 键盘焦点管理和跨浏览器规范化。
- 支持键盘事件,例如 Tab 和 Space 键。
- 为辅助技术提供标签支持。
- 通过 ARIA 暴露为切换控件给辅助技术。
API
Switch 属性
| Prop | Type | Default |
children | | |
value | | |
name | | |
size | | "md" |
color | | "primary" |
thumbIcon | | |
startContent | | |
endContent | | |
isSelected | | |
defaultSelected | | |
isReadOnly | | |
isDisabled | | false |
disableAnimation | | false |
classNames | |
Switch 事件
| Prop | Type | Default |
onChange | | |
onValueChange | |

