import { Switch } from "@chakra-ui/react"
const Demo = () => {
return (
<Switch.Root>
<Switch.HiddenInput />
<Switch.Control />
<Switch.Label>Activate Chakra</Switch.Label>
</Switch.Root>
)
}
用法
import { Switch } from "@chakra-ui/react"
<Switch.Root>
<Switch.HiddenInput />
<Switch.Control>
<Switch.Thumb />
</Switch.Control>
<Switch.Label />
</Switch.Root>
信息
如果您偏好封闭式组件组合,请查看下面的代码片段。快捷方式
Switch
组件还为常见用例提供了一组快捷方式。
开关控制器
Switch.Control
默认在其内部渲染 Switch.Thumb
。
这样可行
<Switch.Control>
<Switch.Thumb />
</Switch.Control>
如果您不需要自定义滑块,这可能会更简洁
<Switch.Control />
示例
尺寸
将 size
属性传递给 Switch.Root
组件以改变开关组件的尺寸。
import { For, HStack, Switch } from "@chakra-ui/react"
const Demo = () => {
return (
<HStack gap="8">
<For each={["xs", "sm", "md", "lg"]}>
{(size) => (
<Switch.Root key={size} size={size}>
<Switch.HiddenInput />
<Switch.Control />
<Switch.Label />
</Switch.Root>
)}
</For>
</HStack>
)
}
变体
将 variant
属性传递给 Switch.Root
组件以改变开关的视觉样式。
import { For, HStack, Switch } from "@chakra-ui/react"
const Demo = () => {
return (
<HStack gap="8">
<For each={["raised", "solid"]}>
{(variant) => (
<Switch.Root key={variant} variant={variant}>
<Switch.HiddenInput />
<Switch.Control />
<Switch.Label />
</Switch.Root>
)}
</For>
</HStack>
)
}
颜色
将 colorPalette
属性传递给 Switch.Root
组件以改变组件的配色方案。
灰色
红色
绿色
蓝色
青色
粉色
紫色
青色
橙色
黄色
import { Stack, Switch, Text } from "@chakra-ui/react"
import { colorPalettes } from "compositions/lib/color-palettes"
const Demo = () => {
return (
<Stack gap="2" align="flex-start">
{colorPalettes.map((colorPalette) => (
<Stack
align="center"
key={colorPalette}
direction="row"
gap="10"
px="4"
>
<Text minW="8ch">{colorPalette}</Text>
<Switch.Root colorPalette={colorPalette}>
<Switch.HiddenInput />
<Switch.Control />
<Switch.Label />
</Switch.Root>
<Switch.Root colorPalette={colorPalette} defaultChecked>
<Switch.HiddenInput />
<Switch.Control />
<Switch.Label />
</Switch.Root>
</Stack>
))}
</Stack>
)
}
受控
使用 checked
和 onCheckedChange
属性来控制开关的状态。
"use client"
import { Switch } from "@chakra-ui/react"
import { useState } from "react"
const Demo = () => {
const [checked, setChecked] = useState(false)
return (
<Switch.Root
checked={checked}
onCheckedChange={(e) => setChecked(e.checked)}
>
<Switch.HiddenInput />
<Switch.Control>
<Switch.Thumb />
</Switch.Control>
<Switch.Label />
</Switch.Root>
)
}
Hook 表单
这是一个将开关与 react-hook-form
集成的示例。
"use client"
import { Button, Field, Stack, Switch } from "@chakra-ui/react"
import { zodResolver } from "@hookform/resolvers/zod"
import { Controller, useForm } from "react-hook-form"
import { z } from "zod"
const formSchema = z.object({
active: z.boolean({ message: "Active is required" }),
})
type FormData = z.infer<typeof formSchema>
const Demo = () => {
const {
handleSubmit,
control,
formState: { errors },
} = useForm<FormData>({
resolver: zodResolver(formSchema),
})
return (
<form onSubmit={handleSubmit((data) => console.log(data))}>
<Stack align="flex-start">
<Controller
name="active"
control={control}
render={({ field }) => (
<Field.Root invalid={!!errors.active}>
<Switch.Root
name={field.name}
checked={field.value}
onCheckedChange={({ checked }) => field.onChange(checked)}
>
<Switch.HiddenInput onBlur={field.onBlur} />
<Switch.Control />
<Switch.Label>Activate Chakra</Switch.Label>
</Switch.Root>
<Field.ErrorText>{errors.active?.message}</Field.ErrorText>
</Field.Root>
)}
/>
<Button size="sm" type="submit" mt="4">
Submit
</Button>
</Stack>
</form>
)
}
禁用
将 disabled
属性传递给 Switch.Root
组件以禁用开关。
import { Switch } from "@chakra-ui/react"
const Demo = () => {
return (
<Switch.Root disabled>
<Switch.HiddenInput />
<Switch.Control />
<Switch.Label>Activate Chakra</Switch.Label>
</Switch.Root>
)
}
无效
将 invalid
属性传递给 Switch.Root
组件以指示开关的错误状态。
import { Switch } from "@chakra-ui/react"
const Demo = () => {
return (
<Switch.Root invalid>
<Switch.HiddenInput />
<Switch.Control />
<Switch.Label>Activate Chakra</Switch.Label>
</Switch.Root>
)
}
工具提示
这是一个如何将开关与工具提示组合的示例。
import { Switch } from "@chakra-ui/react"
import { Tooltip } from "@/components/ui/tooltip"
import { useId } from "react"
const Demo = () => {
const id = useId()
return (
<Tooltip ids={{ trigger: id }} content="This is a tooltip">
<Switch.Root ids={{ root: id }}>
<Switch.HiddenInput />
<Switch.Control />
<Switch.Label>Switch with tooltip</Switch.Label>
</Switch.Root>
</Tooltip>
)
}
轨道指示器
使用 Switch.Indicator
组件根据选中状态显示不同的指示器。
"use client"
import { Icon, Switch } from "@chakra-ui/react"
import { FaMoon, FaSun } from "react-icons/fa"
const Demo = () => {
return (
<Switch.Root colorPalette="blue" size="lg">
<Switch.HiddenInput />
<Switch.Control>
<Switch.Thumb />
<Switch.Indicator fallback={<Icon as={FaMoon} color="gray.400" />}>
<Icon as={FaSun} color="yellow.400" />
</Switch.Indicator>
</Switch.Control>
<Switch.Label>Switch me</Switch.Label>
</Switch.Root>
)
}
滑块指示器
使用 Switch.ThumbIndicator
组件向开关滑块添加图标。
import { Switch } from "@chakra-ui/react"
import { HiCheck, HiX } from "react-icons/hi"
const Demo = () => {
return (
<Switch.Root size="lg">
<Switch.HiddenInput />
<Switch.Control>
<Switch.Thumb>
<Switch.ThumbIndicator fallback={<HiX color="black" />}>
<HiCheck />
</Switch.ThumbIndicator>
</Switch.Thumb>
</Switch.Control>
<Switch.Label>Switch me</Switch.Label>
</Switch.Root>
)
}
封闭式组件
以下是如何为封闭式组件组合设置 Switch。
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>
)
},
)
如果您想自动将封闭式组件添加到您的项目中,请运行此命令
npx @chakra-ui/cli snippet add switch
以下是使用方法
<Switch>Activate Chakra</Switch>
属性
根
属性 | 默认值 | 类型 |
---|---|---|
value | 'on' | string | number 开关输入的值。对于表单提交很有用。 |
colorPalette | 'gray' | 'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'cyan' | 'purple' | 'pink' 组件的配色方案 |
variant | 'solid' | 'solid' | 'raised' 组件的变体 |
size | 'md' | 'xs' | 'sm' | 'md' | 'lg' 组件的尺寸 |
asChild | ||
checked | boolean 开关是否选中。 | |
disabled | boolean 开关是否禁用。 | |
ids | Partial<{ root: string hiddenInput: string control: string label: string thumb: string }> 开关中元素的 ID。对于组合很有用。 | |
invalid | boolean 如果 | |
label | string 指定用于标识无障碍元素及其状态的本地化字符串 | |
name | string 开关中输入字段的名称(对于表单提交很有用)。 | |
onCheckedChange | (details: CheckedChangeDetails) => void 点击开关时调用的函数。 | |
readOnly | boolean 开关是否只读 | |
required | boolean 如果 | |
as | React.ElementType 要渲染的底层元素。 | |
unstyled | boolean 是否移除组件的样式。 |