JavaScript,React:使用ColorPicker创建一个按钮

时间:2018-10-04 09:57:45

标签: javascript reactjs reactive-programming

我想创建一个带有一些文本的按钮,并且还应该显示上次选择的颜色(如下图所示)。

点击该按钮应启动ColorPicker。如何做到这一点。

2 个答案:

答案 0 :(得分:0)

您需要使用会话或cookie来获取最后选择的颜色。到目前为止,这就是我完成的事情。

document.getElementById('color-picker').addEventListener('change', function(){
      var color = document.getElementById('color-picker').value;
      document.getElementById('color-holder').style.backgroundColor = color;
      document.getElementById('color-holder').style.borderColor = color;
    });
.mother-div{
        position: relative;
        width: 80px;
      }
      .color-holder{
        width: 50px;
        height: 50px;
        border-radius: 50%;
        border: 1px solid black;
        display: inline-block;
      }
      i {
        border: solid black;
        height: 10px;
        width: 10px;
        border-width: 0 3px 3px 0;
        display: inline-block;
        padding: 3px;
        position: absolute;
        right: 0px;
        top: 12px;
        border-color: grey;
        }
      .down {
        transform: rotate(45deg);
        -webkit-transform: rotate(45deg);
        }
<div class="mother-div">
      <label>
        <div class="color-holder" id='color-holder'></div>
        <i class="down"></i>
        <input type="color" style="display:none;" id="color-picker">
      </label>
    </div>

答案 1 :(得分:0)

反应版本检查一下:

index.js

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
      color: []
    };
  }

  ItemChecked(e){
     var tValue = e.target.value;
     this.setState({ color: tValue });
  }  

  render() {
    return (
      <div>
      <label>
        <div class="result" style={{backgroundColor:this.state.color}}></div>
        <input type="color" id="color-picker" ref="color-value" onChange={this.ItemChecked.bind(this)} />  
        <span class="select"></span> 
      </label>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

css

h1, p {
  font-family: Lato;
}

.result {
  border: 1px solid #333;
  border-radius: 50%;
  width: 50px;
  height: 50px;
}

#color-picker {
  display: none;
}

.select {
  cursor: pointer;
  position: absolute;
  left: 65px;
  top: 27px;
}

.select:before{
    content: "▼";
}

https://stackblitz.com/edit/react-xx2pjw?file=index.js