# 组合

> 构建自定义 React 颜色选择器：给面板添加自己的模式，或基于颜色 store 和 hook 驱动自己的界面，共享同一个颜色。

Source: https://chroma-panel.jscrate.dev/zh/react/handbook/composition
Last updated: 2026-09-21

如果你的界面应当放在 `ChromaPanel` 里面，就添加一个自定义模式。如果要在面板之外做一套不同的布局，就使用颜色 store 和 hook。

## 在面板内：自定义模式

模式只是普通数据，所以新增一个模式不需要改动任何现有文件：

```tsx
import { registerMode, ChromaPanel } from "chroma-panel";

registerMode({
  id: "brand",
  label: "Brand colors",
  icon: BrandIcon,
  Panel: BrandPanel, // reads the color with usePanel()
});

<ChromaPanel modes={["wheel", "brand"]} />;
```

在 `BrandPanel` 中，你可以使用面板自带的控件，比如 [ColorArea](https://chroma-panel.jscrate.dev/zh/react/components/color-area)、[ChannelSlider](https://chroma-panel.jscrate.dev/zh/react/components/channel-slider)、[Swatch](https://chroma-panel.jscrate.dev/zh/react/components/swatch) 等。它们通过 `usePanel()` 读取颜色，所以只能在 `ChromaPanel` 内部使用。

更多内容见[自定义模式](https://chroma-panel.jscrate.dev/zh/react/modes/custom)。

## 在面板外：store 和 hook

如果选择器不在 `ChromaPanel` 里，就创建一个 store，再用 hook 读取它。`createColorStore` 来自[颜色引擎](https://chroma-panel.jscrate.dev/zh/react/utils/color-engine)入口，这个入口不依赖 React。

```tsx
import { createColorStore } from "chroma-panel/core";
import { useColorValue } from "chroma-panel";

const store = createColorStore({ h: 220, s: 75, v: 80, a: 1 });

function Preview() {
  const color = useColorValue(store);

  return <div style={{ background: `hsl(${color.h} 50% 50%)` }} />;
}
```

> **这些基础组件不能单独使用**
>
> `ColorArea`、`ChannelSlider` 等组件都通过 `usePanel()` 读取颜色，在
> `ChromaPanel` 之外渲染它们是无法工作的。请改用 `createColorStore` 和 hook。

## 在多个面板间共享一个颜色

把同一个 store 传给多个组件，它们就会保持同步。这种做法可以替代在每个组件上分别[控制颜色值](https://chroma-panel.jscrate.dev/zh/react/handbook/controlled)。

```tsx
const store = createColorStore({ h: 220, s: 75, v: 80, a: 1 });

<ChromaPanel store={store} />
<ColorInput store={store} />
```

详见 [useColorStore](https://chroma-panel.jscrate.dev/zh/react/utils/use-color-store)。
