当前位置: 首页 > 工具软件 > react-color > 使用案例 >

react-color一个不错的颜色选择组件

谯皓君
2023-12-01

一个不错的选择颜色组件

import { SketchPicker } from 'react-color';
import React, { useState, useEffect } from 'react';
import { Popover } from 'antd';
import { SketchPicker } from 'react-color';
import styles from './index.less';

const ColorPicker = props => {
  const { value, style, onChange } = props;
  const [color, setColor] = useState({
    r: '255',
    g: '255',
    b: '255',
    a: '1',
  });

  useEffect(() => {
    setColor(value);
  }, [value]);

  return (
    <Popover
      overlayClassName={styles.popover}
      content={
        <SketchPicker
          color={color}
          onChange={hexColor => {
            setColor(hexColor.rgb);
            if (onChange) {
              onChange(hexColor.rgb);
            }
          }}
        />
      }
      trigger="click"
    >
      <div className={styles.swatch} style={{ ...style, background: `rgba(${ color.r }, ${ color.g }, ${ color.b }, ${ color.a })` }}></div>
    </Popover>
  );
};

export default ColorPicker;

index.less

@import '~antd/es/style/themes/default.less';

.popover {
  :global {
    .ant-popover-inner-content {
      padding: 0;
    }
  }
}

.swatch {
  display: inline-block;
  width: 24px;
  height: 24px;
  border: 1px solid rgba(33, 40, 61, 1);
  border-radius: 1px;
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1);
  cursor: pointer;
}

 

 

若没有组件的帮助,只能手动将十六进制颜色转为rgba()数组类型:颜色转化的完整代码

function hextoGamma(hex){
    var gamma = 0.45;
    var gammaCorrection = 1 / gamma;

    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i.exec(hex);
    r = parseInt(result[1], 16);
    g = parseInt(result[2], 16);
    b = parseInt(result[3], 16);
    a = parseInt(result[4], 16) || 255;
    var newColor = [
      Math.pow((r / 255), gammaCorrection),
      Math.pow((g / 255), gammaCorrection),
      Math.pow((b / 255), gammaCorrection),
      Math.pow((a / 255), gammaCorrection)
    ];
    return newColor
}

 

 类似资料: