react-color color picker

A color selector component under the react framework, which is relatively widely used.
Click to go to github react-color of react-color

How to use

1 installation
npm install react-color --save // 或
cnpm install react-color --save // 或
yarn add react-color --save
2typescript declaration

If you are using typescript language to write code, you need to make additional declarations for react-color.
In the src in the root directory, create a type folder, in the folder, create the
react-color.ts file, and write the following code in the file.

declare module 'react-color';
3 quotes on demand

There are many different components in react-color. You can introduce one or a part of them according to your needs. You don’t need to introduce react-color into the project.

// react-color 目前一共有13种组件:
/** <AlphaPicker /> 
 <BlockPicker /> 
 <ChromePicker/> 
 <CirclePicker /> 
 <CompactPicker /> 
 <GithubPicker /> 
 <HuePicker/> 
 <MaterialPicker />
 <PhotoshopPicker /> 
 <SketchPicker/> 
 <SliderPicker/> 
 <SwatchesPicker/>  
 <TwitterPicker/> */
import {
    
     CompactPicker } from 'react-color';
4How to use

The usage of each component is basically the same. Take CompactPicker as an example below

The component receives three parameters color onChange onChangeComplete
color to control the currently selected color on the color selector, which is used to initialize the color, or to keep the color of the parent and child components consistent

onChange is triggered when the color is changed. Each time the color is modified, a function is passed to call. He will be called frequently. If you just want to get the last selected color, use onChangeComplete

onChangeComplete is triggered after the color change is completed, then the color synchronization of the parent and child components can be maintained

import React,{
    
     useState } from 'react';
import {
    
     CompactPicker } from 'react-color';

const ColorPicker = () => {
    
    
/** 支持16进制颜色和rgb哦 */
// const [color, setColor] = useState('rgb(255,255,255)')
const [color, setColor] = useState('#fff')

/** 
colorObj属性如下
hex: "#ffffff"
hsl: {h: 0, s: 0, l: 1, a: 1}
hsv: {h: 0, s: 0, v: 1, a: 1}
oldHue: 0
rgb: {r: 255, g: 255, b: 255, a: 1}
source: "hex"
*/
const onChangeColor = (colorObj) => {
    
    
	setColor(colorObj.hex)
}

/** onChangeCompeleteColor 我测试发现无法触发,可能是这个组件无onChangeComplete,大家可以用其它组件试试看 */
const onChangeCompeleteColor = (colorObj) => {
    
    
	console.log(colorObj)
}

return <CompactPicker color={
    
    color} onChange={
    
    onChangeColor} onChangeComplete={
    
    onChangeCompeleteColor } /> 
}

export default ColorPicker;

Guess you like

Origin blog.csdn.net/glorydx/article/details/114285402