配合表单使用的颜色选择器:https://www.jianshu.com/p/b7bc59146058,原文react hooks版本的,我改成的class函数版本的。
1.安装:
npm install react-color --save
2.封装:colorPicker.js
import React, { FC } from 'react'; import { SketchPicker } from 'react-color'; class ColorPicker extends React.Component { constructor() { super(); this.state={ displayColorPicker:false, color:"#6A8F2E", } } handleClick = () => { const {displayColorPicker} = this.state this.setState({ displayColorPicker: !displayColorPicker }); }; handleClose = () => { this.setState({ displayColorPicker: false }); }; handleChange = ({ hex }) => { const {onChange} = this.props; this.setState({ color: hex }); // eslint-disable-next-line no-unused-expressions onChange && onChange(hex); }; render() { const {displayColorPicker,color} =this.state; return ( <div> <div style={{ padding: '5px', background: '#fff', borderRadius: '1px', boxShadow: '0 0 0 1px rgba(0,0,0,.1)', display: 'inline-block', cursor: 'pointer', }} onClick={this.handleClick} > <div style={{ width: '36px', height: '14px', borderRadius: '2px', background: color, }} /> </div> {displayColorPicker ? ( <div style={{ position: 'absolute', zIndex: '2', }} > <div style={{ position: 'fixed', top: '0px', right: '0px', bottom: '0px', left: '0px', }} onClick={this.handleClose} /> <SketchPicker color={color} onChange={this.handleChange} /> </div> ) : null} </div> ) } } export default ColorPicker;
3.使用:引入和表单使用的部分代码
import ColorPicker from "../colorPicker"; <Form {...formItemLayout} layout='vertical' onSubmit={this.okHandler}> <FormItem label="节点标题"> {getFieldDecorator('name', { rules: [ { required: true, message: '节点名称不可为空', }, { max: 100, message: '字符限制100个', }, ], initialValue: elementName, })(<Input placeholder="请输入节点名称" />)} </FormItem> <FormItem label="节点颜色"> {getFieldDecorator('color', { initialValue: "#6A8F2E", })( <ColorPicker />)} </FormItem> </Form>
使用还是挺方便的。标签:displayColorPicker,ColorPicker,color,hex,react,选择器 From: https://www.cnblogs.com/class1/p/18325589