1 | import React, {
|
2 | PropTypes,
|
3 | Component,
|
4 | } from 'react';
|
5 |
|
6 | import {
|
7 | Animated,
|
8 | Text,
|
9 | View,
|
10 | } from 'react-native';
|
11 |
|
12 | export default class BaseInput extends Component {
|
13 |
|
14 | static propTypes = {
|
15 | label: PropTypes.string,
|
16 | value: PropTypes.string,
|
17 | style: View.propTypes.style,
|
18 | inputStyle: Text.propTypes.style,
|
19 | labelStyle: Text.propTypes.style,
|
20 | easing: PropTypes.func,
|
21 | animationDuration: PropTypes.number,
|
22 |
|
23 | |
24 |
|
25 |
|
26 | onBlur: PropTypes.func,
|
27 | onFocus: PropTypes.func,
|
28 | onChange: PropTypes.func,
|
29 | };
|
30 |
|
31 | constructor(props, context) {
|
32 | super(props, context);
|
33 |
|
34 | this._onLayout = this._onLayout.bind(this);
|
35 | this._onChange = this._onChange.bind(this);
|
36 | this._onBlur = this._onBlur.bind(this);
|
37 | this._onFocus = this._onFocus.bind(this);
|
38 | this._focus = this._focus.bind(this);
|
39 |
|
40 | this.state = {
|
41 | value: props.value,
|
42 | focusedAnim: new Animated.Value(props.value ? 1 : 0),
|
43 | };
|
44 | }
|
45 |
|
46 | componentWillReceiveProps(newProps) {
|
47 | const newValue = newProps.value;
|
48 | if (newValue !== this.state.value) {
|
49 | this.setState({
|
50 | value: newValue,
|
51 | });
|
52 |
|
53 |
|
54 |
|
55 | const isFocused = this.refs.input.isFocused();
|
56 | if (!isFocused) {
|
57 | const isActive = Boolean(newValue);
|
58 | if (isActive !== this.isActive) {
|
59 | this._toggle(isActive);
|
60 | }
|
61 | }
|
62 | }
|
63 | }
|
64 |
|
65 | _onLayout(event) {
|
66 | this.setState({
|
67 | width: event.nativeEvent.layout.width,
|
68 | });
|
69 | }
|
70 |
|
71 | _onChange(event) {
|
72 | this.setState({
|
73 | value: event.nativeEvent.text,
|
74 | });
|
75 |
|
76 | const onChange = this.props.onChange;
|
77 | if (onChange) {
|
78 | onChange(event);
|
79 | }
|
80 | }
|
81 |
|
82 | _onBlur(event) {
|
83 | if (!this.state.value) {
|
84 | this._toggle(false);
|
85 | }
|
86 |
|
87 | const onBlur = this.props.onBlur;
|
88 | if (onBlur) {
|
89 | onBlur(event);
|
90 | }
|
91 | }
|
92 |
|
93 | _onFocus(event) {
|
94 | this._toggle(true);
|
95 |
|
96 | const onFocus = this.props.onFocus;
|
97 | if (onFocus) {
|
98 | onFocus(event);
|
99 | }
|
100 | }
|
101 |
|
102 | _focus() {
|
103 | this.refs.input.focus();
|
104 | }
|
105 |
|
106 | _toggle(isActive) {
|
107 | this.isActive = isActive;
|
108 | Animated.timing(
|
109 | this.state.focusedAnim, {
|
110 | toValue: isActive ? 1 : 0,
|
111 | duration: this.props.animationDuration,
|
112 | easing: this.props.easing,
|
113 | },
|
114 | ).start();
|
115 | }
|
116 | }
|