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

基于react的颜色拾取器(react-color)

米修平
2023-12-01

官方文档:http://casesandberg.github.io/react-color/#api-onChangeComplete

组件的封装:

let React = require('react');
import { SketchPicker } from 'react-color';
export default class ColorSelect extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      color:props.color,
      key:props.objKey,
      displayColorPicker: "none",
    };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick = ()=> {
    let {displayColorPicker,key,color} =this.state;
    displayColorPicker = displayColorPicker=="none"?"block":"none";
    this.setState({displayColorPicker})
    if(displayColorPicker){
        this.props.updateColor(key,color)
    }
  }
  handleChange = (value)=>{
      let color = value.hex;
      this.setState({color})
    
  }
  render() {
      let {color,displayColorPicker} = this.state;
    return (
      <div>
        <button onClick={ this.handleClick } style={{background:color,border:"none",lineHeight:"31px",height:31,width:45,verticalAlign: "middle"}}></button> //button色块样式
        {displayColorPicker=="block"?
        <div style={{position:"absolute",zIndex:66}}> //是选择器脱离标准流
            <SketchPicker color={this.state.color}  onChange={this.handleChange} />
        </div>
        :null
        }
      </div>
    );
  }
}

组件的使用:

import ColorSelect from './ColorPicker'

<ColorSelect 
 style={{ verticalAlign: "middle" }}
 color={useContent[key].color} //编辑的时候,用于颜色的回显
 objKey = {key} //因页面多次使用,传入key值,用于区分色块更新,因key是关键字,这里使用了objKey作为属性名                                                                          
 updateColor = {this.updateColor} //传入父组件方法,更新颜色的拾取                                                                        ></ColorSelect>   

 

 类似资料: