-
-
Notifications
You must be signed in to change notification settings - Fork 227
/
Input.jsx
130 lines (112 loc) · 2.73 KB
/
Input.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import Autosize from 'autosize';
class Input extends PureComponent {
constructor(props) {
super(props);
this.state = {
length: (props.value || props.defaultValue || '').length,
};
this.onInputChange = this.onInputChange.bind(this);
}
componentDidMount() {
this.initAutosize();
}
componentDidUpdate(prevProps) {
if (prevProps.style !== this.props.style ||
prevProps.className !== this.props.className) {
Autosize.update(this.input);
}
}
componentWillUnmount() {
this.destroyAutosize();
}
onInputChange(e) {
const { onChange } = this.props;
this.setState({
length: e.target.value.length,
});
typeof onChange === 'function' && onChange(e);
}
// 初始化自适应高度
initAutosize() {
const { autosize } = this.props;
autosize && Autosize(this.input);
}
// 销毁自适应高度
destroyAutosize() {
const { autosize } = this.props;
autosize && Autosize.destroy(this.input);
}
render() {
const {
prefixCls,
className,
placeholder,
type,
maxLength,
disabled,
autosize,
showLength,
...others
} = this.props;
const cls = classnames({
[`${prefixCls}`]: true,
[className]: !!className,
disabled,
});
const inputRender = (type === 'textarea')
? (
<textarea
{...others}
ref={(ele) => { this.input = ele; }}
className={cls}
placeholder={placeholder}
disabled={disabled}
onChange={this.onInputChange}
/>
)
: (
<input
{...others}
ref={(ele) => { this.input = ele; }}
type={type}
className={cls}
placeholder={placeholder}
disabled={disabled}
onChange={this.onInputChange}
/>
);
const valueRender = (type === 'date')
? <div className={`${prefixCls}-placeholder`}>{placeholder}</div>
: null;
const textLengthRender = (showLength && maxLength)
? <div className={`${prefixCls}-length`}>{`${this.state.length}/${maxLength}`}</div>
: null;
return (
<div className={cls}>
{valueRender}
{inputRender}
{textLengthRender}
</div>
);
}
}
Input.propTypes = {
prefixCls: PropTypes.string,
className: PropTypes.string,
type: PropTypes.string,
disabled: PropTypes.bool,
autosize: PropTypes.bool,
showLength: PropTypes.bool,
};
Input.defaultProps = {
prefixCls: 'za-input',
className: null,
type: 'text',
disabled: false,
autosize: false,
showLength: false,
};
export default Input;