Swatch 是一个 React 色块:把一个颜色画成一个按钮。点击时,它会用自己的 color 调用 onSelect。传了 label 时,屏幕阅读器播报 label;没传时则播报颜色字符串。所以命名颜色要起一个真正的名字,比如「Brand blue」,而不是 #3366cc。round 会把它画成圆形而不是圆角方形,disabled 则让它无法选择。
Swatch 本身不会改变选择器的颜色。点击后发生什么由你的 onSelect 决定,在自定义模式中通常是先解析字符串,再交给面板的 store,就像下面的例子这样。如果只是在自己的布局里放几个颜色,就用它。要按行展示一整组颜色,请使用 SwatchGrid,调色板模式和预设色模式都是基于它构建的。
结构
import { Swatch, parse, usePanel } from "chroma-panel";
function BrandSwatch() {
const { store } = usePanel();
return (
<Swatch
color="#3366cc"
label="Brand blue"
onSelect={(color) => {
const next = parse(color);
if (next !== null) {
store.ingest(next);
store.commit();
}
}}
/>
);
}随处可用
Swatch 自己不会读取面板。上面的示例调用了 usePanel(),正是这一步把它和
ChromaPanel 关联起来。在面板之外,请用你自己的 state 或一个颜色
store 来处理 onSelect。
API 参考
Props
| Prop | Type | Default | Description |
|---|---|---|---|
| color* | string | — | The color it shows and reports. Any CSS color string. |
| label | string | the color string | Accessible name. Give named swatches a real name rather than a hex value. |
| matchKey | string | the color string | The value compared against the current color to decide the selected ring. Set it when the displayed color is not what selection should match on. |
| round | boolean | false | Render as a circle instead of a rounded square. |
| disabled | boolean | false | Makes the swatch unselectable. |
| onSelect | (color: string) => void | — | Fires with the color when chosen. |
| className | string | — | Class on the swatch. |
相关内容
- SwatchGrid:按行排列的多个色块,已经和面板连接好
- 调色板模式:内置的具名色块组
- 解析:把返回的字符串转换为 HSVA 值
- useColorStore:
ingest和commit的作用