如果选择器可以自己管理弹出层,就用 ColorInput。如果希望由 Material UI 控制浮层、间距和打开状态,就把 ChromaPanel 放进 MUI Popover 或 Dialog。
安装
npm install chroma-panel不需要 Material UI 适配器。chroma-panel 的运行时不包含 MUI,所以你的应用会继续使用已有的版本。
使用 ColorInput
ColorInput 可以作为独立字段,放在 MUI 控件旁边。它的值和表单其余部分放在同一个状态里即可。
import { useState } from "react";
import { ColorInput } from "chroma-panel";
import { FormControl, FormLabel, Stack } from "@mui/material";
export function AccentColorField() {
const [color, setColor] = useState("#1976d2");
return (
<FormControl>
<FormLabel>Accent color</FormLabel>
<Stack direction="row" alignItems="center" spacing={1}>
<ColorInput
value={color}
onChange={(next) => setColor(next.hex)}
aria-label="Accent color"
/>
<code>{color}</code>
</Stack>
</FormControl>
);
}把 ChromaPanel 放进 MUI Popover
使用内联组件,这样页面上只有一个弹出层和一个焦点管理器。
import { useState, type MouseEvent } from "react";
import { ChromaPanel } from "chroma-panel";
import { Button, Popover } from "@mui/material";
export function MuiColorPicker() {
const [anchor, setAnchor] = useState<HTMLElement | null>(null);
const [color, setColor] = useState("#1976d2");
const open = Boolean(anchor);
return (
<>
<Button
variant="outlined"
aria-haspopup="dialog"
aria-expanded={open}
onClick={(event: MouseEvent<HTMLButtonElement>) =>
setAnchor(event.currentTarget)
}
>
Choose color
</Button>
<Popover
open={open}
anchorEl={anchor}
onClose={() => setAnchor(null)}
anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
slotProps={{
paper: {
sx: { mt: 1, overflow: "visible", bgcolor: "transparent" },
},
}}
>
<ChromaPanel
value={color}
onChange={(next) => setColor(next.hex)}
showTitleBar={false}
/>
</Popover>
</>
);
}MUI Popover 负责处理外部点击、焦点和滚动锁定。在这种用法下,ChromaPanel 只负责颜色交互。MUI Dialog、Drawer 或 Menu 也可以用同样的方式;模态框的细节请看模态框中的选择器。
匹配 MUI 主题
通过主题或外层类名设置面板的 CSS 变量。可以先从 --cp-accent、--cp-focus、--cp-surface 和 --cp-radius-lg 开始。完整列表见主题指南。