hexColor.tsx 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import * as React from "react";
  2. export interface IHexColorProps {
  3. value: string,
  4. expectedLength: number,
  5. onChange: (value: string) => void
  6. }
  7. export class HexColor extends React.Component<IHexColorProps, {hex: string}> {
  8. constructor(props: IHexColorProps) {
  9. super(props);
  10. this.state = {hex: this.props.value.replace("#", "")}
  11. }
  12. shouldComponentUpdate(nextProps: IHexColorProps, nextState: {hex: string}) {
  13. if (nextProps.value!== this.props.value) {
  14. nextState.hex = nextProps.value.replace("#", "");
  15. }
  16. return true;
  17. }
  18. updateHexValue(valueString: string) {
  19. if (valueString != "" && /^[0-9A-Fa-f]+$/g.test(valueString) == false) {
  20. return;
  21. }
  22. this.setState({hex: valueString});
  23. if(valueString.length !== this.props.expectedLength) {
  24. return;
  25. }
  26. this.props.onChange("#" + valueString);
  27. }
  28. public render() {
  29. return (
  30. <input type="string" className="hex-input" value={this.state.hex}
  31. onChange={evt => this.updateHexValue(evt.target.value)}/>
  32. )
  33. }
  34. }