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

React应用react-color

刘奇
2023-12-01

一、 安装与引入

 	安装:
 	
 		npm install react-color --save 
 		
 	引入:
 		import React from 'react'
 		
		import { SketchPicker } from 'react-color'
		
		class Component extends React.Component {
		
  			render() {
  			
    			return <SketchPicker />
    			
  			}
  			
		}	

二、实际开发中(案例)

1、 父组件调用封装的color

<Color 
		defaultColor={backgroundColor} 
		align={'right'} 
		setColor={(hex: string) => { setBackgroundColor(hex) }} 
/>

2. 封装处理数据,引入color供给父组件使用

index.tsx


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

interface ColorProps{
  size?: 'small' | 'middle' | 'large'
  setColor: Function;
  defaultColor?: string;
  align?: 'left' | 'right'
}
const Color: React.FC<ColorProps> = (props) => {
  const { setColor, defaultColor, size, align='left' } = props;
  const [displayColorPicker, setDisplayColorPicker] = useState(false)
  const [backgroundColor, setBackgroundColor] = useState(defaultColor || '#F3B74B')

  useEffect(()=>{
    setBackgroundColor(defaultColor as string)
  }, [defaultColor])

  return (
    <div className={classnames({
      [styles.colorBox]: true,
      [styles.small]: size === 'small',
    })}>
      <div className={styles.swatch} onClick={() => {
        setDisplayColorPicker(true)
      }} >
        <div className={styles.hex}>{backgroundColor}</div>
        <div className={styles.color} style={{ backgroundColor: backgroundColor }} />
      </div>
      {displayColorPicker ? <div className={classnames({
        [styles.popover]: true,
        [styles.left]: align === 'left',
        [styles.right]: align === 'right',
      })}>
        <div className={styles.cover} onClick={() => setDisplayColorPicker(false)} />
        <SketchPicker color={backgroundColor} onChange={(color) => {
          let hex = color.hex || '';
          let hexUpperCase = hex.toLocaleUpperCase();
          setBackgroundColor(hexUpperCase)
          setColor(hexUpperCase)
        }} />
      </div> : null}
    </div>
  )
}

export default Color;

index.less


.popover{
  position: absolute;
  z-index: 2;
  &.left{
    left: 0;
  }
  &.right{
    right: 0;
  }
}
.colorBox{
  position: relative;
  input{
    line-height: 1;
  }
  span{
    line-height: 1;
  }
  input{
    box-sizing: content-box;
  }
}

.swatch{
  width: 110px;
  padding: 3px 5px;
  background: #fff;
  border-radius: 1px;
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.2);
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
}
.hex{
  font-size: 12px;
}

.color{
  width: 25px;
  height: 25px;
  border-radius: 2px;
  background: rgba(0, 0, 0, 1);
  margin-left: 10px;
}

.cover{
  position: fixed;
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;
}


.small{
  .swatch{
    width: 100px;
  }
  .color{
    width: 20px;
    height: 20px;
  }
}
 类似资料: