OSDN Git Service

f5e403ce1f3b4ecfe708578899511593e1b7ceef
[bytom/bytom-electron.git] / src / features / shared / components / AmountInputMask / AmountInputMask.jsx
1 import React from 'react'
2 import { parseBTMAmount, formatBTMAmount, addZeroToDecimalPosition } from 'utility/buildInOutDisplay'
3 import { FieldLabel } from 'features/shared/components'
4 import pick from 'lodash/pick'
5
6
7 const TEXT_FIELD_PROPS = [
8   'value',
9   'onBlur',
10   'onChange',
11   'onFocus',
12   'name'
13 ]
14
15 class AmountInputMask extends React.Component {
16   constructor(props) {
17     super(props)
18
19     this.state = {
20       value: props.fieldProps.value,
21     }
22
23     this.handleChange = this.handleChange.bind(this)
24     this.handleBlur = this.handleBlur.bind(this)
25   }
26
27
28   handleBlur(event) {
29     const value = event.target.value
30     this.setState({ value: addZeroToDecimalPosition( value, this.props.decimal ) })
31     if (this.props.fieldProps.onBlur) {
32       // Swallow the event to prevent Redux Form from
33       // extracting the form value
34       this.props.fieldProps.onBlur()
35     }
36   }
37
38   handleChange(event) {
39     const value = event.target.value
40     // Update the internal state to trigger a re-render
41     // using the formatted value
42     this.setState({ value: value })
43     if (this.props.fieldProps.onChange) {
44       // Notify the normalized value
45       this.props.fieldProps.onChange(
46         parseBTMAmount(value, this.props.decimal )
47       )
48     }
49   }
50
51   render() {
52     const fieldProps = pick(this.props.fieldProps, TEXT_FIELD_PROPS)
53     const {touched, error} = this.props.fieldProps
54
55     return(
56       <div className='form-group'>
57         {this.props.title && <FieldLabel>{this.props.title}</FieldLabel>}
58           <input className='form-control'
59             type={'text'}
60             {...fieldProps}
61             value={formatBTMAmount(this.state.value, this.props.decimal)}
62             placeholder={this.props.placeholder}
63             autoFocus={!!this.props.autoFocus}
64             onBlur={this.handleBlur}
65             onChange={this.handleChange}
66           />
67         {touched && error && <span className='text-danger'><strong>{error}</strong></span>}
68         {this.props.hint && <span className='help-block'>{this.props.hint}</span>}
69       </div>
70     )
71   }
72 }
73
74 export default AmountInputMask