11import React , { Component } from 'react' ;
22import styled from 'styled-components' ;
33import { KEY_CODES } from 'common/constants' ;
4+ import { pastFromClipboard } from 'common/utils/clipboard' ;
45
56const StyledInput = styled . input `
67 width: 40px;
@@ -24,6 +25,24 @@ export class CodeItem extends Component {
2425 value : '' ,
2526 } ;
2627
28+ static getDerivedStateFromProps ( nextProps ) {
29+ // The state without cache is a reasonable solution for this place.
30+ return {
31+ value : nextProps . value ,
32+ } ;
33+ }
34+
35+ onPaste = e => {
36+ // Stop the data being pasted into the element.
37+ e . stopPropagation ( ) ;
38+ e . preventDefault ( ) ;
39+
40+ const pastedData = pastFromClipboard ( e ) ;
41+ if ( pastedData != null && pastedData . length > 0 ) {
42+ this . props . onPaste ( pastedData ) ;
43+ }
44+ } ;
45+
2746 onKeyDown = e => {
2847 const {
2948 onBackspace,
@@ -48,17 +67,12 @@ export class CodeItem extends Component {
4867 onChange = e => {
4968 const value = this . validate ( e . target . value ) ;
5069 if ( this . state . value === value ) return ;
51- if ( value . length < 2 ) {
52- this . setState ( { value } ) ;
53- this . props . onChange ( value ) ;
54- }
70+ this . setState ( { value } ) ;
71+ this . props . onChange ( value ) ;
5572 } ;
5673
5774 validate = value => {
58- const numCode = value . charCodeAt ( 0 ) ;
59- const isInteger =
60- numCode >= '0' . charCodeAt ( 0 ) && numCode <= '9' . charCodeAt ( 0 ) ;
61- return isInteger ? value : '' ;
75+ return / ^ [ 0 - 9 ] $ / . test ( value ) ? value : '' ;
6276 } ;
6377
6478 render ( ) {
@@ -69,6 +83,7 @@ export class CodeItem extends Component {
6983 < StyledInput
7084 onChange = { this . onChange }
7185 onKeyDown = { this . onKeyDown }
86+ onPaste = { this . onPaste }
7287 maxLength = "1"
7388 autoComplete = "off"
7489 ref = { createRef }
0 commit comments