開關

開關組件用於在勾選與未勾選狀態之間切換。


安裝

上述命令僅適用於個別安裝。如果 @nextui-org/react 已全域安裝,您可以跳過此步驟。

導入

用法

帶有標籤

已停用

尺寸

顏色

帶有拇指標示

帶有圖示

您也可以使用 startContentendContent 屬性,在開關的開頭和結尾添加圖示。

受控元件

注意:NextUI 的 Switch 也支援原生事件,例如 onChange,這對於像是 FormikReact Hook Form 等表單函式庫非常有用。

插槽

  • base:開關的基本插槽。它是主要的包裝器。
  • wrapper:開始圖示、結束圖示和滑塊的包裝器。
  • hiddenInput:用於處理開關狀態的隱藏輸入元素。
  • thumb:開關的滑塊元素。它是圓形元素。
  • label:開關的標籤插槽。
  • startContent:開關開頭的圖示插槽。
  • endContent:開關結尾的圖示插槽。
  • thumbIcon:滑塊內的圖示插槽。

自訂樣式

您可以透過將自訂的 Tailwind CSS 類別傳遞到元件的插槽,來自訂 Switch 元件。

自訂實作

如果您需要進一步自訂開關,可以使用 useSwitch Hook 來建立您自己的實作。

資料屬性

Switchbase 元素上具有以下屬性

  • data-selected:當開關被選取時。基於 isSelected 屬性。
  • data-pressed:當按下開關時。基於 usePress
  • data-readonly:當開關為唯讀時。基於 isReadOnly 屬性。
  • data-hover:當滑鼠懸停在開關上時。基於 useHover
  • data-focus:當開關被聚焦時。基於 useFocusRing
  • data-focus-visible:當使用鍵盤聚焦開關時。基於 useFocusRing
  • data-disabled:當開關被禁用時。基於 isDisabled 屬性。

輔助功能

  • 使用原生的 HTML <input> 元素建構。
  • 完整支援瀏覽器功能,例如表單自動填寫。
  • 鍵盤焦點管理和跨瀏覽器標準化。
  • 支援 TabSpace 鍵的鍵盤事件。
  • 為輔助技術提供標籤支援。
  • 透過 ARIA 向輔助技術公開為開關。

API

Switch 屬性

屬性類型預設值
children
ReactNode
value
string
name
string
size
sm | md | lg
"md"
color
default | primary | secondary | success | warning | danger
"primary"
thumbIcon
ThumbIconProps
startContent
ReactNode
endContent
ReactNode
isSelected
boolean
defaultSelected
boolean
isReadOnly
boolean
isDisabled
boolean
false
disableAnimation
boolean
false
classNames
Partial<Record<"base"| "wrapper"| "thumb"| "label" | "startContent" | "endContent" | "thumbIcon" , string>>

開關事件

屬性類型預設值
onChange
React.ChangeEvent<HTMLInputElement>
onValueChange
(isSelected: boolean) => void

類型

開關圖示屬性