Skip to Content
文档

开关

用于捕获二进制状态。

SourceStorybookRecipeArk

用法

¥Usage

import { Switch } from "@chakra-ui/react"
<Switch.Root>
  <Switch.HiddenInput />
  <Switch.Control>
    <Switch.Thumb />
  </Switch.Control>
  <Switch.Label />
</Switch.Root>
info

如果你更喜欢封闭的组件组合,请查看 以下代码片段

¥If you prefer a closed component composition, check out the snippet below.

快捷键

¥Shortcuts

Switch 组件还提供了一组用于常见用例的快捷方式。

¥The Switch component also provides a set of shortcuts for common use cases.

SwitchControl

Switch.Control 默认在其内部渲染 Switch.Thumb

¥The Switch.Control renders the Switch.Thumb within it by default.

有效:

¥This works:

<Switch.Control>
  <Switch.Thumb />
</Switch.Control>

如果你不需要自定义拇指,这可能会更简洁:

¥This might be more concise, if you don't need to customize the thumb:

<Switch.Control />

示例

¥Examples

尺寸

¥Sizes

size 属性传递给 Switch.Root 组件,以更改开关组件的大小。

¥Pass the size prop to the Switch.Root component to change the size of the switch component.

变量

¥Variants

variant 属性传递给 Switch.Root 组件,即可更改开关的视觉样式。

¥Pass the variant prop to the Switch.Root component to change the visual style of the switch.

颜色

¥Colors

colorPalette 属性传递给 Switch.Root 组件,即可更改组件的配色方案。

¥Pass the colorPalette prop to the Switch.Root component to change the color scheme of the component.

gray

red

green

blue

teal

pink

purple

cyan

orange

yellow

受控

¥Controlled

使用 checkedonCheckedChange 属性控制开关的状态。

¥Use the checked and onCheckedChange prop to control the state of the switch.

钩子表单

¥Hook Form

以下是如何将开关与 react-hook-form 集成的示例。

¥Here's an example of integrating the switch with react-hook-form.

已禁用

¥Disabled

disabled 属性传递给 Switch.Root 组件,即可禁用开关。

¥Pass the disabled prop to the Switch.Root component to disable the switch.

无效

¥Invalid

invalid 属性传递给 Switch.Root 组件,以指示开关的错误状态。

¥Pass the invalid prop to the Switch.Root component to indicate an error state for the switch.

工具提示

¥Tooltip

以下是如何将开关与工具提示组合的示例。

¥Here's an example of how to compose a switch with a tooltip.

轨道指示器

¥Track Indicator

使用 Switch.Indicator 组件根据选中状态显示不同的指示符。

¥Use the Switch.Indicator component to display different indicators based on the checked state.

缩略图指示器

¥Thumb Indicator

使用 Switch.ThumbIndicator 组件为开关按钮添加图标。

¥Use the Switch.ThumbIndicator component to add an icon to the switch thumb.

已关闭组件

¥Closed Component

以下是如何设置封闭组件组合的开关。

¥Here's how to setup the Switch for a closed component composition.

import { Switch as ChakraSwitch } from "@chakra-ui/react"
import * as React from "react"

export interface SwitchProps extends ChakraSwitch.RootProps {
  inputProps?: React.InputHTMLAttributes<HTMLInputElement>
  rootRef?: React.RefObject<HTMLLabelElement | null>
  trackLabel?: { on: React.ReactNode; off: React.ReactNode }
  thumbLabel?: { on: React.ReactNode; off: React.ReactNode }
}

export const Switch = React.forwardRef<HTMLInputElement, SwitchProps>(
  function Switch(props, ref) {
    const { inputProps, children, rootRef, trackLabel, thumbLabel, ...rest } =
      props

    return (
      <ChakraSwitch.Root ref={rootRef} {...rest}>
        <ChakraSwitch.HiddenInput ref={ref} {...inputProps} />
        <ChakraSwitch.Control>
          <ChakraSwitch.Thumb>
            {thumbLabel && (
              <ChakraSwitch.ThumbIndicator fallback={thumbLabel?.off}>
                {thumbLabel?.on}
              </ChakraSwitch.ThumbIndicator>
            )}
          </ChakraSwitch.Thumb>
          {trackLabel && (
            <ChakraSwitch.Indicator fallback={trackLabel.off}>
              {trackLabel.on}
            </ChakraSwitch.Indicator>
          )}
        </ChakraSwitch.Control>
        {children != null && (
          <ChakraSwitch.Label>{children}</ChakraSwitch.Label>
        )}
      </ChakraSwitch.Root>
    )
  },
)

如果你想自动将封闭式组件添加到项目中,请运行以下命令:

¥If you want to automatically add the closed component to your project, run the command:

npx @chakra-ui/cli snippet add switch

以下是如何使用它

¥Here's how to use the it

<Switch>Activate Chakra</Switch>

属性

¥Props

根元素

¥Root

PropDefaultType
value '\'on\''
string | number

The value of switch input. Useful for form submission.

colorPalette 'gray'
'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'cyan' | 'purple' | 'pink'

The color palette of the component

variant 'solid'
'solid' | 'raised'

The variant of the component

size 'md'
'xs' | 'sm' | 'md' | 'lg'

The size of the component

as
React.ElementType

The underlying element to render.

asChild
boolean

Use the provided child element as the default rendered element, combining their props and behavior.

For more details, read our Composition guide.
unstyled
boolean

Whether to remove the component's style.

checked
boolean

The controlled checked state of the switch

disabled
boolean

Whether the switch is disabled.

ids
Partial<{ root: string; hiddenInput: string; control: string; label: string; thumb: string }>

The ids of the elements in the switch. Useful for composition.

invalid
boolean

If `true`, the switch is marked as invalid.

label
string

Specifies the localized strings that identifies the accessibility elements and their states

name
string

The name of the input field in a switch (Useful for form submission).

onCheckedChange
(details: CheckedChangeDetails) => void

Function to call when the switch is clicked.

readOnly
boolean

Whether the switch is read-only

required
boolean

If `true`, the switch input is marked as required,

Previous

选择(原生)

Next

滑块