React Color使用

需求

- 要在react项目中实现颜色获取器功能

解决方案

- 使用react-color 依赖

https://github.com/casesandberg/react-color

http://casesandberg.github.io/react-color/#api-onChange

使用

1. 安装react color 依赖

yarn add react-color @types/react-color
  • 项目中没有使用typescript时,不需要@types/react-color

2. 按需引入

import React from 'react';
import { SketchPicker } from 'react-color';

function ColorPicker  {
  const [color, setColor] = useState("#333");

  render() {
    return <SketchPicker 
                color={color}
                onChangeComplete={ (color:any)=>setColor(color.hex) }
           />;
  }
}
  • 除了SketchPicker,还有ChromePhotoshopBlockGithubTwitterHueAlphaCircleSliderCompactMaterialSwatches几种,可以根据需要引入相应组件。

API

1. color

  • 颜色选择器颜色选中值,即可接收hex'#333',也可以接受rgb{ r: 51, g: 51, b: 51, a: 1 },也可以接受hsl{ h: 0, s: 0, l: .10, a: 1 }

2. onChange

  • 每次颜色改变都会触发该方法,返回color对象color:{hex: '#333', rgb: {r: 51, g: 51, b: 51, a: 1 },hsl:{ h: 0, s: 0, l: .10, a: 1 }

3. onChangeComplete

  • 颜色选择完成后触发该方法,与onChange类似,我理解是onChange的优化,onChange触发相对频繁,如果仅是获取选中的颜色,使用onChangeComplete即可。