直接看效果
组件代码
type EyeDropper &#61; {open: (options?: { signal?: AbortSignal }) &#61;> Promise<{ sRGBHex: string | undefined }>;
};function useEyeDropper(init?: string,): [state: { canUse: boolean; color: string },action: (signal?: AbortSignal | undefined) &#61;> Promise<string | undefined>,] {const canUse &#61; useMemo(function () {return Object.prototype.hasOwnProperty.call(window, &#39;EyeDropper&#39;);}, []);const [color, setColor] &#61; useState(init ?? &#39;&#39;);const open &#61; useCallback(async function (signal?: AbortSignal) {if (!canUse) return;const eyeDropper: EyeDropper &#61; new (window as any).EyeDropper();const res &#61; await eyeDropper.open({ signal });res.sRGBHex && setColor(res.sRGBHex);return res.sRGBHex;},[canUse],);return [{ canUse, color }, open];}
使用example
const [{ color }, open] &#61; useEyeDropper();const handleClick &#61; useCallback(() &#61;> {open();}, [open]);<><button onClick&#61;{handleClick}>点击</button><span>颜色:{color}</span>
<div style&#61;{{ display: &#39;flex&#39; }}><div style&#61;{{ width: &#39;20px&#39;, height: &#39;20px&#39;, backgroundColor: &#39;#fff&#39; }}></div><div style&#61;{{ width: &#39;20px&#39;, height: &#39;20px&#39;, backgroundColor: &#39;#fff222&#39; }}></div><div style&#61;{{ width: &#39;20px&#39;, height: &#39;20px&#39;, backgroundColor: &#39;#f99999&#39; }}></div><div style&#61;{{ width: &#39;20px&#39;, height: &#39;20px&#39;, backgroundColor: &#39;#f22111&#39; }}></div></div></>