ChannelSlider 是一个 React 颜色滑块,用来调节当前颜色的某一个通道,比如色相、红色、亮度或不透明度。通道由你来指定:read 从颜色中取出一个数值,write 把新数值合并回颜色。滑块模式中 RGB、HSL 和 HSB 的每一行,以及色轮模式中的亮度和不透明度滑块,都是由这个组件绘制的。
如果自定义模式需要一个内置模式里没有的滑块,就可以用它。gradient 为当前颜色绘制轨道,shortLabel 在轨道旁显示一个字母(如 H),formatValue 为屏幕阅读器播报的内容加上单位,例如「Hue 210 degrees」。拖动时颜色每一帧都会更新,松手时才提交,所以每次拖动只触发一次 onChangeComplete。
结构
import { ChannelSlider } from "chroma-panel";
<ChannelSlider
label="Hue"
min={0}
max={360}
read={(c) => c.h}
write={(h, c) => ({ ...c, h })}
/>;轨道是一个真正的 <input type="range">,所以键盘操作和屏幕阅读器播报都由浏览器负责。支持的按键见无障碍功能。
只能在面板内使用
内置模式就是由这些基础组件搭起来的。它通过 usePanel() 读取颜色,所以只能放在 ChromaPanel 里使用,通常用在自定义模式中。如果要在面板之外做颜色选择器,请使用颜色 store 和相关 hook。
API 参考
Props
| Prop | Type | Default | Description |
|---|---|---|---|
| label* | string | — | Accessible name, announced as text — "Hue 210 degrees", not a bare number. |
| shortLabel | string | — | The letter shown beside the track, such as H. Leave it out to show no letter. |
| min* | number | — | Lowest value the channel takes. |
| max* | number | — | Highest value the channel takes. |
| step | number | 1 | Arrow-key increment. Page Up and Page Down take the larger steps a native range input uses. |
| read* | (color: Hsva) => number | — | Pulls this channel's value out of the current color. |
| write* | (value: number, current: Hsva) => Hsva | — | Merges a new value back into the color. Returning a whole Hsva rather than one channel is what preserves hue at the extremes. |
| gradient | (color: Hsva) => string | — | Builds the CSS gradient painted behind the track for the current color. Omit for a plain track. |
| channel | string | — | Sets data-cp-channel on the track, so CSS can target one channel. |
| formatValue | (value: number) => string | — | Formats the announced value, for units the label cannot carry. Defaults to the rounded number. |
| className | string | — | Class on the slider row. |
相关内容
- 滑块模式:每个通道都是一个 ChannelSlider,支持 RGB、HSL 或 HSB
- NumberField:对应的数字输入版本,同样使用
read和write - 转换:在
read和write中进行 HSVA、RGBA 与 HSLA 之间的转换 - 无障碍功能:整个选择器的键盘和屏幕阅读器支持