React實現(xiàn)隨機顏色選擇器的示例代碼
背景
在標(biāo)簽功能中,由于有「背景色」屬性,每次新增標(biāo)簽時都為選擇哪種顏色犯難。因此,我們思考如何通過JS代碼生成隨機顏色,提取一個通用的隨機顏色生成工具,并基于React框架封裝隨機顏色選擇器組件。
實際效果
原理與思路
作為前端開發(fā)人員,我們知道HTML接受 RGB、HEX、HSL三種格式的顏色。雖然是不同的格式,但是它們的本質(zhì)都是通過數(shù)字表達出顏色。
因為RGB、HEX、HSL 本身都是數(shù)字,那么通過生成隨機數(shù)并組裝成符合格式要求的數(shù)字,也就達到預(yù)期隨機生成顏色的想法。
下面分別列舉RGB和HEX格式的隨機顏色生成思路
- 以RGB格式為例,rbg(0,0,0)代表黑色,rbg(255,255,255)代表白色。所以我們通過JS的Math.random方法隨機生成3個0~255之間的隨機數(shù),并且取整,將生成的三個隨機數(shù)進行字符串拼接即可得到一個RGB格式的顏色。
- 以HEX格式為例,#000000代表黑色, #FFFFFF代表白色??梢园l(fā)現(xiàn)hex格式通常都是6位16進制的數(shù)字,每兩位16進制數(shù)字分為一組,比如1~2位代表red,3~4代表blue,5~6代表green。同樣的道理,通過Math.random方法隨機生成3個0~255之間的隨機數(shù),通過JS的toString(16)方法將10進制隨機數(shù)轉(zhuǎn)化成16進制格式,最后通過字符串拼接得到HEX格式的顏色。
核心代碼
- RBG格式隨機顏色生成方法
export function getRandomRGBColor(limit: number = 256) { //十六進制顏色隨機 const r = Math.floor(Math.random() * limit); const g = Math.floor(Math.random() * limit); const b = Math.floor(Math.random() * limit); const color = `rgb(${r},${g},$)`; return color; }
- HEX格式隨機顏色生成方法
export function getRandomHEXColor(limit: number = 256) { const getRandomHexNumber = (limit: number): string => { let randomNum = Math.floor(Math.random() * limit).toString(16); if (randomNum.length < 2) { randomNum = "0" + randomNum; } return randomNum; }; //十六進制顏色隨機 const r = getRandomHexNumber(limit); const g = getRandomHexNumber(limit); const b = getRandomHexNumber(limit); const color = `#${r}${g}$`; return color; }
React組件
這是標(biāo)簽背景隨機顏色選擇器的React組件代碼,實現(xiàn)是非常簡單的,可以直接復(fù)制使用。
實際運行效果可以看本文最開始的「實際效果」截圖。
import { useMemo, useState } from "react"; import { getRandomColor } from "@/utils/color"; import classnames from "classnames"; import { Check, Refresh } from "@icon-park/react"; import { nanoid } from "nanoid"; interface ColorSelectProps { defaultValue: string; value?: string; onChange?: (value: string) => void; } export default function ColorSelect(props: ColorSelectProps) { const { defaultValue, value, onChange } = props; // 用于重新生成顏色 const [randomId, setRandomId] = useState(""); const colors = useMemo(() => { // 隨機生成6個顏色 return new Array(6).fill(0).map(() => getRandomColor()); }, [randomId]); const targetColors = useMemo(() => { // 過濾是否存在默認(rèn)值的情況 return [...colors, defaultValue || ""].filter( v => !!v && !["#"].includes(v), ); }, [defaultValue, colors]); return ( <div className="flex gap-2"> {targetColors.map(color => { console.log("color--->", color); return ( <div key={color} data-color={color} onClick={() => onChange?.(color)} className={classnames( "h-8 w-8 cursor-pointer flex justify-center items-center", )} style={{ backgroundColor: color }}> {value === color && ( <Check theme="multi-color" size="24" fill="#fff" /> )} </div> ); })} <div className="h-8 w-8 cursor-pointer flex justify-center items-center border border-solid border-color-BGBrown text-color-BGBrown text-P4-Regular" onClick={() => setRandomId(nanoid())}> <Refresh theme="outline" size="18" fill="#333" /> </div> </div> ); }
到此這篇關(guān)于React實現(xiàn)隨機顏色選擇器的示例代碼的文章就介紹到這了,更多相關(guān)React 隨機顏色選擇器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
react?hooks?UI與業(yè)務(wù)邏輯分離必要性技術(shù)方案
這篇文章主要為大家介紹了react?hooks?UI與業(yè)務(wù)邏輯分離必要性技術(shù)方案詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11React項目中動態(tài)插入HTML內(nèi)容的實現(xiàn)
本文主要介紹了React項目中動態(tài)插入HTML內(nèi)容的實現(xiàn),通過使用React的dangerouslySetInnerHTML屬性,我們可以將HTML內(nèi)容插入到組件中,具有一定的參考價值,感興趣的可以了解一下2023-10-10