import { Slider } from "@chakra-ui/react"
const Demo = () => {
return (
<Slider.Root width="200px" defaultValue={[40]}>
<Slider.Control>
<Slider.Track>
<Slider.Range />
</Slider.Track>
<Slider.Thumbs />
</Slider.Control>
</Slider.Root>
)
}
用法
¥Usage
import { Slider } from "@chakra-ui/react"
<Slider.Root>
<Slider.Label />
<Slider.ValueText />
<Slider.Control>
<Slider.Track>
<Slider.Range />
</Slider.Track>
<Slider.Thumb>
<Slider.DraggingIndicator />
<Slider.HiddenInput />
</Slider.Thumb>
<Slider.MarkerGroup>
<Slider.Marker />
</Slider.MarkerGroup>
</Slider.Control>
</Slider.Root>
如果你更喜欢封闭的组件组合,请查看 以下代码片段。
¥If you prefer a closed component composition, check out the snippet below.
快捷键
¥Shortcuts
Slider.Thumbs
此组件为每个值渲染 Slider.Thumb
和 Slider.HiddenInput
组件。
¥This component renders the Slider.Thumb
and Slider.HiddenInput
components
for each value.
以下代码有效:
¥The code below works:
<Slider.Thumb index={0}>
<Slider.HiddenInput />
</Slider.Thumb>
但如果你不需要自定义缩略图,以下代码可能会更好:
¥but this might be better if you don't need to customize the thumb:
<Slider.Thumbs />
Slider.Marks
此组件为每个值渲染 Slider.MarkerGroup
和 Slider.Marker
组件。
¥This component renders the Slider.MarkerGroup
and Slider.Marker
components
for each value.
以下代码有效:
¥The code below works:
<Slider.MarkerGroup>
<Slider.Marker value={0} />
<Slider.Marker value={50} />
</Slider.MarkerGroup>
但如果你不需要自定义标记,以下代码可能会更好:
¥but this might be better if you don't need to customize the marker:
<Slider.Marks marks={[0, 50]} />
示例
¥Examples
尺寸
¥Sizes
使用 size
属性更改滑块的大小。
¥Use the size
prop to change the size of the slider.
import { For, Slider, Stack } from "@chakra-ui/react"
const Demo = () => {
return (
<Stack width="200px" gap="4">
<For each={["sm", "md", "lg"]}>
{(size) => (
<Slider.Root defaultValue={[40]} size={size} key={size}>
<Slider.Label>Slider - {size}</Slider.Label>
<Slider.Control>
<Slider.Track>
<Slider.Range />
</Slider.Track>
<Slider.Thumbs />
</Slider.Control>
</Slider.Root>
)}
</For>
</Stack>
)
}
变量
¥Variants
使用 variant
属性更改滑块的视觉样式。
¥Use the variant
prop to change the visual style of the slider.
import { For, Slider, Stack } from "@chakra-ui/react"
const Demo = () => {
return (
<Stack width="200px" gap="4">
<For each={["outline", "solid"]}>
{(variant) => (
<Slider.Root defaultValue={[40]} variant={variant} key={variant}>
<Slider.Label>Slider - {variant}</Slider.Label>
<Slider.Control>
<Slider.Track>
<Slider.Range />
</Slider.Track>
<Slider.Thumbs />
</Slider.Control>
</Slider.Root>
)}
</For>
</Stack>
)
}
颜色
¥Colors
使用 colorPalette
属性更改滑块的颜色。
¥Use the colorPalette
prop to change the color of the slider.
import { For, Slider, Stack } from "@chakra-ui/react"
const colors = ["gray", "blue", "red", "green", "pink"]
const Demo = () => {
return (
<Stack gap="4" align="flex-start">
<For each={colors}>
{(color) => (
<Slider.Root
key={color}
width="200px"
colorPalette={color}
defaultValue={[40]}
>
<Slider.Control>
<Slider.Track>
<Slider.Range />
</Slider.Track>
<Slider.Thumbs />
</Slider.Control>
</Slider.Root>
)}
</For>
</Stack>
)
}
标签
¥Label
使用 label
属性为滑块添加标签。
¥Use the label
prop to add a label to the slider.
import { Slider } from "@chakra-ui/react"
const Demo = () => {
return (
<Slider.Root width="200px" defaultValue={[40]}>
<Slider.Label>Quantity</Slider.Label>
<Slider.Control>
<Slider.Track>
<Slider.Range />
</Slider.Track>
<Slider.Thumbs />
</Slider.Control>
</Slider.Root>
)
}
范围滑块
¥Range Slider
将 value
或 defaultValue
属性设置为数组,以创建范围滑块。
¥Set the value
or defaultValue
prop to an array to create a range slider.
import { Slider } from "@chakra-ui/react"
const Demo = () => {
return (
<Slider.Root width="200px" defaultValue={[30, 60]}>
<Slider.Control>
<Slider.Track>
<Slider.Range />
</Slider.Track>
<Slider.Thumbs />
</Slider.Control>
</Slider.Root>
)
}
防止重叠
¥Prevent Overlap
使用 minStepsBetweenThumbs
属性避免缩略图具有相同的值。
¥Use the minStepsBetweenThumbs
prop to avoid thumbs with the same value.
import { Slider } from "@chakra-ui/react"
const Demo = () => {
return (
<Slider.Root maxW="md" defaultValue={[20, 60]} minStepsBetweenThumbs={8}>
<Slider.Control>
<Slider.Track>
<Slider.Range />
</Slider.Track>
<Slider.Thumbs />
</Slider.Control>
</Slider.Root>
)
}
自定义
¥Customization
以下是使用自定义图标和背景自定义缩略图的示例。
¥Here's an example of customizing the thumb with custom icon and background.
"use client"
import { Box, Slider } from "@chakra-ui/react"
import { MdGraphicEq } from "react-icons/md"
const Demo = () => {
return (
<Slider.Root defaultValue={[30]}>
<Slider.Control>
<Slider.Track bg="red.100">
<Slider.Range bg="tomato" />
</Slider.Track>
<Slider.Thumb index={0} boxSize={6} borderColor="tomato" shadow="md">
<Box color="tomato" as={MdGraphicEq} />
</Slider.Thumb>
</Slider.Control>
</Slider.Root>
)
}
值文本
¥Value Text
使用 Slider.ValueText
组件显示滑块的当前值。
¥Use the Slider.ValueText
component to show the current value of the slider.
import { HStack, Slider } from "@chakra-ui/react"
const Demo = () => {
return (
<Slider.Root maxW="sm" size="sm" defaultValue={[40]}>
<HStack justify="space-between">
<Slider.Label>Volume</Slider.Label>
<Slider.ValueText />
</HStack>
<Slider.Control>
<Slider.Track>
<Slider.Range />
</Slider.Track>
<Slider.Thumbs rounded="l1" />
</Slider.Control>
</Slider.Root>
)
}
受控
¥Controlled
使用 value
和 onValueChange
属性控制滑块的值。
¥Use the value
and onValueChange
props to control the value of the slider.
"use client"
import { Slider } from "@chakra-ui/react"
import { useState } from "react"
const Demo = () => {
const [value, setValue] = useState([40])
return (
<Slider.Root
maxW="200px"
value={value}
onValueChange={(e) => setValue(e.value)}
>
<Slider.Control>
<Slider.Track>
<Slider.Range />
</Slider.Track>
<Slider.Thumbs />
</Slider.Control>
</Slider.Root>
)
}
商店
¥Store
控制滑块的另一种方法是使用 RootProvider
组件和 useSlider
存储钩子。
¥An alternative way to control the slider is to use the RootProvider
component
and the useSlider
store hook.
这样,你就可以从滑块外部访问滑块状态和方法。
¥This way you can access the slider state and methods from outside the slider.
current: 40
"use client"
import { Code, Slider, Stack, useSlider } from "@chakra-ui/react"
const Demo = () => {
const slider = useSlider({
defaultValue: [40],
thumbAlignment: "center",
})
return (
<Stack align="flex-start">
<Code>current: {slider.value}</Code>
<Slider.RootProvider value={slider} width="200px">
<Slider.Label>Slider</Slider.Label>
<Slider.Control>
<Slider.Track>
<Slider.Range />
</Slider.Track>
<Slider.Thumbs />
</Slider.Control>
</Slider.RootProvider>
</Stack>
)
}
钩子表单
¥Hook Form
以下是如何将滑块与 react-hook-form
集成的示例。
¥Here's an example of how to integrate a slider with react-hook-form
.
"use client"
import { Button, Field, Slider, Stack } 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({
value: z.array(
z
.number({ message: "Value is required" })
.min(60, { message: "Value must be greater than 60" }),
),
})
type FormValues = z.infer<typeof formSchema>
const Demo = () => {
const {
control,
handleSubmit,
formState: { errors },
} = useForm<FormValues>({
resolver: zodResolver(formSchema),
defaultValues: { value: [40] },
})
const onSubmit = handleSubmit((data) => console.log(data))
return (
<form onSubmit={onSubmit}>
<Stack align="flex-start" gap="4" maxW="300px">
<Controller
name="value"
control={control}
render={({ field }) => (
<Field.Root invalid={!!errors.value?.length}>
<Field.Label>Slider: {field.value[0]}</Field.Label>
<Slider.Root
width="full"
name={field.name}
value={field.value}
onValueChange={({ value }) => {
field.onChange(value)
}}
onFocusChange={({ focusedIndex }) => {
if (focusedIndex !== -1) return
field.onBlur()
}}
>
<Slider.Control>
<Slider.Track>
<Slider.Range />
</Slider.Track>
<Slider.Thumbs />
</Slider.Control>
</Slider.Root>
<Field.ErrorText>{errors.value?.[0]?.message}</Field.ErrorText>
</Field.Root>
)}
/>
<Button size="sm" type="submit">
Submit
</Button>
</Stack>
</form>
)
}
已禁用
¥Disabled
使用 disabled
属性禁用滑块。
¥Use the disabled
prop to disable the slider.
import { Slider } from "@chakra-ui/react"
const Demo = () => {
return (
<Slider.Root width="200px" disabled defaultValue={[40]}>
<Slider.Control>
<Slider.Track>
<Slider.Range />
</Slider.Track>
<Slider.Thumbs />
</Slider.Control>
</Slider.Root>
)
}
更改结束
¥Change End
使用 onValueChangeEnd
属性监听滑块变化的结束。
¥Use the onValueChangeEnd
prop to listen to the end of the slider change.
onChange: 50
onChangeEnd: 50
"use client"
import { Box, Code, Slider, Stack } from "@chakra-ui/react"
import { useState } from "react"
const initialValue = [50]
const Demo = () => {
const [value, setValue] = useState(initialValue)
const [endValue, setEndValue] = useState(initialValue)
return (
<Box maxW="240px">
<Slider.Root
value={value}
onValueChange={(e) => setValue(e.value)}
onValueChangeEnd={(e) => setEndValue(e.value)}
>
<Slider.Control>
<Slider.Track>
<Slider.Range />
</Slider.Track>
<Slider.Thumbs />
</Slider.Control>
</Slider.Root>
<Stack mt="3" gap="1">
<Code>
onChange: <b>{value}</b>
</Code>
<Code>
onChangeEnd: <b>{endValue}</b>
</Code>
</Stack>
</Box>
)
}
步骤
¥Steps
使用 step
属性设置滑块的步长值。
¥Use the step
prop to set the step value of the slider.
import { Slider } from "@chakra-ui/react"
const Demo = () => {
return (
<Slider.Root width="200px" defaultValue={[40]} step={10}>
<Slider.Control>
<Slider.Track>
<Slider.Range />
</Slider.Track>
<Slider.Thumbs />
</Slider.Control>
</Slider.Root>
)
}
缩略图对齐方式
¥Thumb Alignment
使用 thumbAlignment
和 thumbSize
属性,在轨道内对齐拇指。默认情况下,滑块与轨道起点对齐。
¥Use the thumbAlignment
and thumbSize
prop to align the thumb within the
track. By default, the thumb is aligned to the start of the track.
import { Slider, Stack } from "@chakra-ui/react"
const Demo = () => {
return (
<Stack maxW="200px" gap="4">
<Slider.Root
thumbAlignment="contain"
thumbSize={{ width: 16, height: 16 }}
defaultValue={[40]}
>
<Slider.Label>Slider (contain)</Slider.Label>
<Slider.Control>
<Slider.Track>
<Slider.Range />
</Slider.Track>
<Slider.Thumbs />
</Slider.Control>
</Slider.Root>
<Slider.Root thumbAlignment="center" defaultValue={[40]}>
<Slider.Label>Slider (center)</Slider.Label>
<Slider.Control>
<Slider.Track>
<Slider.Range />
</Slider.Track>
<Slider.Thumbs />
</Slider.Control>
</Slider.Root>
</Stack>
)
}
标记
¥Marks
使用 marks
属性在滑块上显示标记。
¥Use the marks
prop to display marks on the slider.
size = sm
size = md
size = lg
import { For, Slider, Stack, Text, VStack } from "@chakra-ui/react"
const Demo = () => {
return (
<Stack gap="4">
<For each={["sm", "md", "lg"]}>
{(size) => (
<VStack key={size} align="flex-start">
<Slider.Root
key={size}
size={size}
defaultValue={[40]}
width="200px"
>
<Slider.Control>
<Slider.Track>
<Slider.Range />
</Slider.Track>
<Slider.Thumbs />
<Slider.Marks marks={[0, 50, 100]} />
</Slider.Control>
</Slider.Root>
<Text>size = {size}</Text>
</VStack>
)}
</For>
</Stack>
)
}
你还可以使用 marks
属性为标记添加标签。
¥You can also add labels to the marks using the marks
prop.
import { Slider } from "@chakra-ui/react"
const marks = [
{ value: 0, label: "0%" },
{ value: 50, label: "50%" },
{ value: 100, label: "100%" },
]
const Demo = () => {
return (
<Slider.Root width="200px" colorPalette="pink" defaultValue={[40]}>
<Slider.Control>
<Slider.Track>
<Slider.Range />
</Slider.Track>
<Slider.Thumbs />
<Slider.Marks marks={marks} />
</Slider.Control>
</Slider.Root>
)
}
垂直
¥Vertical
使用 orientation
属性更改滑块的方向。
¥Use the orientation
prop to change the orientation of the slider.
import { Slider } from "@chakra-ui/react"
const Demo = () => {
return (
<Slider.Root height="200px" orientation="vertical" defaultValue={[40]}>
<Slider.Control>
<Slider.Track>
<Slider.Range />
</Slider.Track>
<Slider.Thumbs />
</Slider.Control>
</Slider.Root>
)
}
垂直对齐标记
¥Vertical with Marks
这是一个带有标记的垂直滑块示例。
¥Here's an example of a vertical slider with marks.
import { Slider } from "@chakra-ui/react"
const marks = [
{ value: 0, label: "0%" },
{ value: 50, label: "50%" },
{ value: 100, label: "100%" },
]
const Demo = () => {
return (
<Slider.Root
height="200px"
orientation="vertical"
colorPalette="pink"
defaultValue={[40]}
>
<Slider.Control>
<Slider.Track>
<Slider.Range />
</Slider.Track>
<Slider.Thumbs />
<Slider.Marks marks={marks} />
</Slider.Control>
</Slider.Root>
)
}
拖动指示器
¥Dragging Indicator
渲染 Slider.DraggingIndicator
组件,在拖动拇指按钮时显示指示符或工具提示。
¥Render the Slider.DraggingIndicator
component to show an indicator or tooltip
when dragging the thumb.
专业提示:你可以在 Slider.DraggingIndicator
内部渲染 Slider.ValueText
组件以显示当前值。
import { Slider } from "@chakra-ui/react"
const Demo = () => {
return (
<Slider.Root maxW="200px" defaultValue={[40]}>
<Slider.Control>
<Slider.Track>
<Slider.Range />
</Slider.Track>
<Slider.Thumb index={0}>
<Slider.DraggingIndicator
layerStyle="fill.solid"
top="6"
rounded="sm"
px="1.5"
>
<Slider.ValueText />
</Slider.DraggingIndicator>
</Slider.Thumb>
</Slider.Control>
</Slider.Root>
)
}
已关闭组件
¥Closed Component
如果你更喜欢封闭式组件组合,请查看以下代码片段。
¥If you prefer a closed component composition, check out the snippet below.
import { Slider as ChakraSlider, HStack } from "@chakra-ui/react"
import * as React from "react"
export interface SliderProps extends ChakraSlider.RootProps {
marks?: Array<number | { value: number; label: React.ReactNode }>
label?: React.ReactNode
showValue?: boolean
}
export const Slider = React.forwardRef<HTMLDivElement, SliderProps>(
function Slider(props, ref) {
const { label, showValue, marks, ...rest } = props
return (
<ChakraSlider.Root ref={ref} thumbAlignment="center" {...rest}>
{label && !showValue && (
<ChakraSlider.Label>{label}</ChakraSlider.Label>
)}
{label && showValue && (
<HStack justify="space-between">
<ChakraSlider.Label>{label}</ChakraSlider.Label>
<ChakraSlider.ValueText />
</HStack>
)}
<ChakraSlider.Control>
<ChakraSlider.Track>
<ChakraSlider.Range />
</ChakraSlider.Track>
<ChakraSlider.Thumbs />
<ChakraSlider.Marks marks={marks} />
</ChakraSlider.Control>
</ChakraSlider.Root>
)
},
)
如果你想自动将封闭式组件添加到项目中,请运行以下命令:
¥If you want to automatically add the closed component to your project, run the command:
npx @chakra-ui/cli snippet add slider
属性
¥Props
Prop | Default | Type |
---|---|---|
max | '100' | number The maximum value of the slider |
min | '0' | number The minimum value of the slider |
minStepsBetweenThumbs | '0' | number The minimum permitted steps between multiple thumbs. `minStepsBetweenThumbs` * `step` should reflect the gap between the thumbs. - `step: 1` and `minStepsBetweenThumbs: 10` => gap is `10` - `step: 10` and `minStepsBetweenThumbs: 2` => gap is `20` |
orientation | 'horizontal' | 'vertical' | 'horizontal' The orientation of the component |
origin | '\'start\'' | 'center' | 'end' | 'start' The origin of the slider range. The track is filled from the origin to the thumb for single values. - "start": Useful when the value represents an absolute value - "center": Useful when the value represents an offset (relative) - "end": Useful when the value represents an offset from the end |
step | '1' | number The step value of the slider |
thumbAlignment | '\'contain\'' | 'center' | 'contain' The alignment of the slider thumb relative to the track - `center`: the thumb will extend beyond the bounds of the slider track. - `contain`: the thumb will be contained within the bounds of the track. |
colorPalette | 'gray' | 'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'cyan' | 'purple' | 'pink' The color palette of the component |
size | 'md' | 'sm' | 'md' | 'lg' The size of the component |
variant | 'outline' | 'outline' | 'solid' The variant 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. | |
aria-label | string[] The aria-label of each slider thumb. Useful for providing an accessible name to the slider | |
aria-labelledby | string[] The `id` of the elements that labels each slider thumb. Useful for providing an accessible name to the slider | |
defaultValue | number[] The initial value of the slider when rendered. Use when you don't need to control the value of the slider. | |
disabled | boolean Whether the slider is disabled | |
form | string The associate form of the underlying input element. | |
getAriaValueText | (details: ValueTextDetails) => string Function that returns a human readable value for the slider thumb | |
id | string The unique identifier of the machine. | |
ids | Partial<{
root: string
thumb: (index: number) => string
hiddenInput: (index: number) => string
control: string
track: string
range: string
label: string
valueText: string
marker: (index: number) => string
}> The ids of the elements in the slider. Useful for composition. | |
invalid | boolean Whether the slider is invalid | |
name | string The name associated with each slider thumb (when used in a form) | |
onFocusChange | (details: FocusChangeDetails) => void Function invoked when the slider's focused index changes | |
onValueChange | (details: ValueChangeDetails) => void Function invoked when the value of the slider changes | |
onValueChangeEnd | (details: ValueChangeDetails) => void Function invoked when the slider value change is done | |
readOnly | boolean Whether the slider is read-only | |
thumbSize | { width: number; height: number } The slider thumbs dimensions | |
value | number[] The controlled value of the slider |