import { Checkbox } from "@chakra-ui/react"
const Demo = () => {
return (
<Checkbox.Root>
<Checkbox.HiddenInput />
<Checkbox.Control />
<Checkbox.Label>Accept terms and conditions</Checkbox.Label>
</Checkbox.Root>
)
}
用法
import { Checkbox } from "@chakra-ui/react"
<Checkbox.Root>
<Checkbox.HiddenInput />
<Checkbox.Control>
<Checkbox.Indicator />
</Checkbox.Control>
<Checkbox.Label />
</Checkbox.Root>
快捷方式
Checkbox
组件还提供了一组用于常见用例的快捷方式。
CheckboxControl
此组件默认在其内部渲染 Checkbox.Indicator
。
这有效
<Checkbox.Control>
<Checkbox.Indicator />
</Checkbox.Control>
如果您不需要自定义指示器,这可能更简洁
<Checkbox.Control />
示例
变体
将 variant
属性传递给 Checkbox.Root
组件以改变复选框的视觉样式。
描边
柔和
实心
import { Checkbox, For, HStack, Stack, Text } from "@chakra-ui/react"
const Demo = () => {
return (
<HStack align="flex-start">
<For each={["outline", "subtle", "solid"]}>
{(variant) => (
<Stack align="flex-start" flex="1" key={variant}>
<Text>{variant}</Text>
<Checkbox.Root defaultChecked variant={variant}>
<Checkbox.HiddenInput />
<Checkbox.Control />
<Checkbox.Label>Checkbox</Checkbox.Label>
</Checkbox.Root>
</Stack>
)}
</For>
</HStack>
)
}
颜色
将 colorPalette
属性传递给 Checkbox.Root
组件以改变复选框的颜色。
灰色
红色
绿色
蓝色
蓝绿色
粉色
紫色
青色
橙色
黄色
import { Checkbox, For, Stack, 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"
width="full"
>
<Text minW="8ch">{colorPalette}</Text>
<For each={["outline", "subtle", "solid"]}>
{(variant) => (
<Stack key={variant} mb="4">
<Checkbox.Root variant={variant} colorPalette={colorPalette}>
<Checkbox.HiddenInput />
<Checkbox.Control />
<Checkbox.Label>Checkbox</Checkbox.Label>
</Checkbox.Root>
<Checkbox.Root
defaultChecked
variant={variant}
colorPalette={colorPalette}
>
<Checkbox.HiddenInput />
<Checkbox.Control />
<Checkbox.Label>Checkbox</Checkbox.Label>
</Checkbox.Root>
</Stack>
)}
</For>
</Stack>
))}
</Stack>
)
}
尺寸
将 size
属性传递给 Checkbox.Root
组件以改变复选框的尺寸。
import { Checkbox, For, Stack } from "@chakra-ui/react"
const Demo = () => {
return (
<Stack align="flex-start" flex="1" gap="4">
<For each={["sm", "md", "lg"]}>
{(size) => (
<Checkbox.Root defaultChecked size={size} key={size}>
<Checkbox.HiddenInput />
<Checkbox.Control />
<Checkbox.Label>Checkbox</Checkbox.Label>
</Checkbox.Root>
)}
</For>
</Stack>
)
}
状态
将 disabled
或 invalid
属性传递给 Checkbox.Root
组件以改变复选框的视觉状态。
import { Checkbox, Stack } from "@chakra-ui/react"
const Demo = () => {
return (
<Stack>
<Checkbox.Root disabled>
<Checkbox.HiddenInput />
<Checkbox.Control />
<Checkbox.Label>Disabled</Checkbox.Label>
</Checkbox.Root>
<Checkbox.Root defaultChecked disabled>
<Checkbox.HiddenInput />
<Checkbox.Control />
<Checkbox.Label>Disabled</Checkbox.Label>
</Checkbox.Root>
<Checkbox.Root readOnly>
<Checkbox.HiddenInput />
<Checkbox.Control />
<Checkbox.Label>Readonly</Checkbox.Label>
</Checkbox.Root>
<Checkbox.Root invalid>
<Checkbox.HiddenInput />
<Checkbox.Control />
<Checkbox.Label>Invalid</Checkbox.Label>
</Checkbox.Root>
</Stack>
)
}
受控
使用 checked
和 onCheckedChange
属性来控制复选框的状态。
"use client"
import { Checkbox } from "@chakra-ui/react"
import { useState } from "react"
const Demo = () => {
const [checked, setChecked] = useState(false)
return (
<Checkbox.Root
checked={checked}
onCheckedChange={(e) => setChecked(!!e.checked)}
>
<Checkbox.HiddenInput />
<Checkbox.Control />
<Checkbox.Label>Accept terms and conditions</Checkbox.Label>
</Checkbox.Root>
)
}
标签位置
这是一个如何将标签位置更改为右侧的示例。
import { Checkbox } from "@chakra-ui/react"
const Demo = () => {
return (
<Checkbox.Root>
<Checkbox.HiddenInput />
<Checkbox.Label>Accept terms and conditions</Checkbox.Label>
<Checkbox.Control />
</Checkbox.Root>
)
}
状态存储
控制复选框的另一种方法是使用 RootProvider
组件和 useCheckbox
状态存储 Hook。
通过这种方式,您可以从复选框外部访问复选框的状态和方法。
"use client"
import { Checkbox, useCheckbox } from "@chakra-ui/react"
const Demo = () => {
const checkbox = useCheckbox()
return (
<Checkbox.RootProvider value={checkbox}>
<Checkbox.Root>
<Checkbox.HiddenInput />
<Checkbox.Control />
<Checkbox.Label>Accept terms and conditions</Checkbox.Label>
</Checkbox.Root>
</Checkbox.RootProvider>
)
}
组合
这是一个如何将复选框与字段组件组合的示例。
"use client"
import { Button, Checkbox, Field, Input, Stack } from "@chakra-ui/react"
const Demo = () => {
return (
<form
onSubmit={(e) => {
e.preventDefault()
console.log(e.currentTarget.elements)
}}
>
<Stack maxW="sm" gap="4" align="flex-start">
<Field.Root>
<Field.Label>Username</Field.Label>
<Input placeholder="username" />
</Field.Root>
<Field.Root>
<Field.Label>Password</Field.Label>
<Input placeholder="password" />
</Field.Root>
<Checkbox.Root mt="2" value="remember me">
<Checkbox.HiddenInput />
<Checkbox.Control />
<Checkbox.Label>Remember me</Checkbox.Label>
</Checkbox.Root>
<Button variant="solid" mt="3">
Submit
</Button>
</Stack>
</form>
)
}
Hook 表单
这是一个如何将 Checkbox
组件与 react-hook-form
库一起使用的示例。
"use client"
import { Button, Checkbox, Code, Field, HStack, Stack } from "@chakra-ui/react"
import { zodResolver } from "@hookform/resolvers/zod"
import { Controller, useController, useForm } from "react-hook-form"
import { z } from "zod"
const formSchema = z.object({
enabled: z.boolean(),
})
type FormData = z.infer<typeof formSchema>
const Demo = () => {
const form = useForm<FormData>({
resolver: zodResolver(formSchema),
defaultValues: { enabled: false },
})
const enabled = useController({
control: form.control,
name: "enabled",
})
const invalid = !!form.formState.errors.enabled
return (
<form onSubmit={form.handleSubmit((data) => console.log(data))}>
<Stack align="flex-start">
<Controller
control={form.control}
name="enabled"
render={({ field }) => (
<Field.Root invalid={invalid} disabled={field.disabled}>
<Checkbox.Root
checked={field.value}
onCheckedChange={({ checked }) => field.onChange(checked)}
>
<Checkbox.HiddenInput />
<Checkbox.Control />
<Checkbox.Label>Checkbox</Checkbox.Label>
</Checkbox.Root>
<Field.ErrorText>
{form.formState.errors.enabled?.message}
</Field.ErrorText>
</Field.Root>
)}
/>
<HStack>
<Button
size="xs"
variant="outline"
onClick={() => form.setValue("enabled", !enabled.field.value)}
>
Toggle
</Button>
<Button size="xs" variant="outline" onClick={() => form.reset()}>
Reset
</Button>
</HStack>
<Button size="sm" type="submit" alignSelf="flex-start">
Submit
</Button>
<Code>Checked: {JSON.stringify(enabled.field.value, null, 2)}</Code>
</Stack>
</form>
)
}
分组
使用 CheckboxGroup
组件将多个复选框组合在一起。
import { Checkbox, CheckboxGroup, Fieldset, For } from "@chakra-ui/react"
const Demo = () => {
return (
<Fieldset.Root>
<CheckboxGroup defaultValue={["react"]} name="framework">
<Fieldset.Legend fontSize="sm" mb="2">
Select framework
</Fieldset.Legend>
<Fieldset.Content>
<For each={["React", "Svelte", "Vue", "Angular"]}>
{(value) => (
<Checkbox.Root key={value} value={value}>
<Checkbox.HiddenInput />
<Checkbox.Control />
<Checkbox.Label>{value}</Checkbox.Label>
</Checkbox.Root>
)}
</For>
</Fieldset.Content>
</CheckboxGroup>
</Fieldset.Root>
)
}
分组 Hook 表单
这是一个如何将 CheckboxGroup
组件与 react-hook-form
库一起使用的示例。
"use client"
import {
Button,
Checkbox,
CheckboxGroup,
Code,
Fieldset,
} from "@chakra-ui/react"
import { zodResolver } from "@hookform/resolvers/zod"
import { useController, useForm } from "react-hook-form"
import { z } from "zod"
const formSchema = z.object({
framework: z.array(z.string()).min(1, {
message: "You must select at least one framework.",
}),
})
type FormData = z.infer<typeof formSchema>
const items = [
{ label: "React", value: "react" },
{ label: "Svelte", value: "svelte" },
{ label: "Vue", value: "vue" },
{ label: "Angular", value: "angular" },
]
const Demo = () => {
const {
handleSubmit,
control,
formState: { errors },
} = useForm<FormData>({
resolver: zodResolver(formSchema),
})
const framework = useController({
control,
name: "framework",
defaultValue: [],
})
const invalid = !!errors.framework
return (
<form onSubmit={handleSubmit((data) => console.log(data))}>
<Fieldset.Root invalid={invalid}>
<Fieldset.Legend>Select your framework</Fieldset.Legend>
<CheckboxGroup
invalid={invalid}
value={framework.field.value}
onValueChange={framework.field.onChange}
name={framework.field.name}
>
<Fieldset.Content>
{items.map((item) => (
<Checkbox.Root key={item.value} value={item.value}>
<Checkbox.HiddenInput />
<Checkbox.Control />
<Checkbox.Label>{item.label}</Checkbox.Label>
</Checkbox.Root>
))}
</Fieldset.Content>
</CheckboxGroup>
{errors.framework && (
<Fieldset.ErrorText>{errors.framework.message}</Fieldset.ErrorText>
)}
<Button size="sm" type="submit" alignSelf="flex-start">
Submit
</Button>
<Code>Values: {JSON.stringify(framework.field.value, null, 2)}</Code>
</Fieldset.Root>
</form>
)
}
自定义图标
在 Checkbox.Control
中渲染自定义图标以改变复选框的图标。
import { Checkbox } from "@chakra-ui/react"
import { HiOutlinePlus } from "react-icons/hi"
const Demo = () => {
return (
<Checkbox.Root defaultChecked>
<Checkbox.HiddenInput />
<Checkbox.Control>
<HiOutlinePlus />
</Checkbox.Control>
<Checkbox.Label>With Custom Icon</Checkbox.Label>
</Checkbox.Root>
)
}
半选状态
将 checked
属性设置为 indeterminate
以将复选框显示为半选状态。
"use client"
import { Checkbox, Stack } from "@chakra-ui/react"
import { useState } from "react"
const initialValues = [
{ label: "Monday", checked: false, value: "monday" },
{ label: "Tuesday", checked: false, value: "tuesday" },
{ label: "Wednesday", checked: false, value: "wednesday" },
{ label: "Thursday", checked: false, value: "thursday" },
]
const Demo = () => {
const [values, setValues] = useState(initialValues)
const allChecked = values.every((value) => value.checked)
const indeterminate = values.some((value) => value.checked) && !allChecked
const items = values.map((item, index) => (
<Checkbox.Root
ms="6"
key={item.value}
checked={item.checked}
onCheckedChange={(e) => {
setValues((current) => {
const newValues = [...current]
newValues[index] = { ...newValues[index], checked: !!e.checked }
return newValues
})
}}
>
<Checkbox.HiddenInput />
<Checkbox.Control />
<Checkbox.Label>{item.label}</Checkbox.Label>
</Checkbox.Root>
))
return (
<Stack align="flex-start">
<Checkbox.Root
checked={indeterminate ? "indeterminate" : allChecked}
onCheckedChange={(e) => {
setValues((current) =>
current.map((value) => ({ ...value, checked: !!e.checked })),
)
}}
>
<Checkbox.HiddenInput />
<Checkbox.Control>
<Checkbox.Indicator />
</Checkbox.Control>
<Checkbox.Label>Weekdays</Checkbox.Label>
</Checkbox.Root>
{items}
</Stack>
)
}
描述
这是一个如何为复选框添加更多描述的示例。
import { Box, Checkbox, Stack } from "@chakra-ui/react"
const Demo = () => {
return (
<Checkbox.Root gap="4" alignItems="flex-start">
<Checkbox.HiddenInput />
<Checkbox.Control />
<Stack gap="1">
<Checkbox.Label>I agree to the terms and conditions</Checkbox.Label>
<Box textStyle="sm" color="fg.muted">
By clicking this, you agree to our Terms and Privacy Policy.
</Box>
</Stack>
</Checkbox.Root>
)
}
链接
在 Checkbox.Label
中渲染一个锚点标签,为标签添加链接。
import { Checkbox, Link } from "@chakra-ui/react"
const Demo = () => {
return (
<Checkbox.Root>
<Checkbox.HiddenInput />
<Checkbox.Control />
<Checkbox.Label>
I agree to the{" "}
<Link colorPalette="teal" href="https://google.com">
terms and conditions
</Link>
</Checkbox.Label>
</Checkbox.Root>
)
}
封闭组件
以下是如何为封闭式组件组合设置 Checkbox。
import { Checkbox as ChakraCheckbox } from "@chakra-ui/react"
import * as React from "react"
export interface CheckboxProps extends ChakraCheckbox.RootProps {
icon?: React.ReactNode
inputProps?: React.InputHTMLAttributes<HTMLInputElement>
rootRef?: React.RefObject<HTMLLabelElement | null>
}
export const Checkbox = React.forwardRef<HTMLInputElement, CheckboxProps>(
function Checkbox(props, ref) {
const { icon, children, inputProps, rootRef, ...rest } = props
return (
<ChakraCheckbox.Root ref={rootRef} {...rest}>
<ChakraCheckbox.HiddenInput ref={ref} {...inputProps} />
<ChakraCheckbox.Control>
{icon || <ChakraCheckbox.Indicator />}
</ChakraCheckbox.Control>
{children != null && (
<ChakraCheckbox.Label>{children}</ChakraCheckbox.Label>
)}
</ChakraCheckbox.Root>
)
},
)
如果您想自动将封闭组件添加到您的项目中,请运行此命令
npx @chakra-ui/cli snippet add checkbox
以下是如何使用它
<Checkbox>Accept terms and conditions</Checkbox>
属性
根
属性 | 默认值 | 类型 |
---|---|---|
value | '\'on\'' | string 复选框输入的值。常用于表单提交。 |
colorPalette | 'gray' | 'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'cyan' | 'purple' | 'pink' 组件的调色板 |
size | 'md' | 'xs' | 'sm' | 'md' | 'lg' 组件的尺寸 |
variant | 'solid' | 'outline' | 'solid' | 'subtle' 组件的变体 |
asChild | ||
checked | CheckedState 复选框的选中状态 | |
defaultChecked | CheckedState 复选框首次渲染时的选中状态。当您不需要控制复选框状态时使用此属性。 | |
disabled | boolean 复选框是否禁用 | |
form | string 复选框所属表单的ID。 | |
id | string 该组件的唯一标识符。 | |
ids | Partial<{ root: string hiddenInput: string control: string label: string }> 复选框中元素的ID。常用于组合。 | |
invalid | boolean 复选框是否无效 | |
name | string 复选框中输入字段的名称。常用于表单提交。 | |
onCheckedChange | (details: CheckedChangeDetails) => void 选中状态改变时调用的回调函数。 | |
readOnly | boolean 复选框是否只读 | |
required | boolean 复选框是否必填 | |
as | React.ElementType 要渲染的底层元素。 | |
unstyled | boolean 是否移除组件的样式。 |