UNPKG

3.54 kBJavaScriptView Raw
1import classnames from 'classnames';
2import React from 'react';
3import PropTypes from 'prop-types';
4
5
6const propTypes = {
7
8 colors: PropTypes.oneOf(['', 'dark', 'success', 'info', 'warning', 'danger', 'primary']),
9
10 disabled: PropTypes.bool,
11
12 inverse: PropTypes.bool
13
14};
15
16const defaultProps = {
17 disabled: false,
18 inverse: false,
19 colors: 'primary',
20 clsPrefix: 'u-checkbox',
21 defaultChecked: false,
22 onClick: function () {}
23};
24const clsPrefix = 'u-checkbox';
25class Checkbox extends React.Component {
26 constructor(props) {
27 super(props);
28 this.state = {
29 checked: 'checked' in props ? props.checked : props.defaultChecked
30 }
31 this.doubleClickFlag = null;
32 }
33
34 componentWillReceiveProps(nextProps) {
35 if ('checked' in nextProps) {
36 this.setState({
37 checked: nextProps.checked,
38 });
39 }
40 }
41
42 changeState = (e) => {
43 const { props } = this;
44 const { checked } = this.state;
45 clearTimeout(this.doubleClickFlag);
46 if(props.onClick instanceof Function){
47 props.onClick(e);
48 }
49 if(props.onDoubleClick instanceof Function){
50 this.doubleClickFlag = setTimeout(() => {
51 //do function在此处写单击事件要执行的代码
52 this.change(props, checked)
53 },300);
54 }else{
55 this.change(props, checked)
56 }
57 e.stopPropagation();
58 e.preventDefault();
59 //执行延时
60 }
61
62 change = (props, checked) => {
63 if (props.disabled) {
64 return;
65 }
66 if (!('checked' in props)) {
67 this.setState({
68 checked: !checked,
69 });
70 }
71
72 if (props.onChange instanceof Function) {
73 props.onChange(!checked);
74 }
75 }
76
77
78 handledbClick = (e) => {
79 const { onDoubleClick } = this.props;
80 clearTimeout(this.doubleClickFlag);
81 onDoubleClick && onDoubleClick(this.state.checked, e);
82 }
83
84 render() {
85 const {
86 disabled,
87 inverse,
88 colors,
89 size,
90 className,
91 indeterminate,
92 onClick,
93 children,
94 checked,
95 clsPrefix,
96 onDoubleClick,
97 onChange,
98 ...others
99 } = this.props;
100
101
102 const input = (
103 <input
104 {...others}
105 type="checkbox"
106 disabled={this.props.disabled}
107 />
108 );
109
110 let classes = {
111 'is-checked': this.state.checked,
112 disabled
113 };
114
115 if (inverse) {
116 classes[`${clsPrefix}-inverse`] = true;
117 }
118
119 if (colors) {
120 classes[`${clsPrefix}-${colors}`] = true;
121 }
122
123 if (size) {
124 classes[`${clsPrefix}-${size}`] = true;
125 }
126
127 if (!checked && indeterminate) {
128 classes[`${clsPrefix}-indeterminate`] = true;
129 }
130
131 let classNames = classnames(clsPrefix, classes);
132
133
134 return (
135 <label
136 className={classnames(classNames, className)}
137 onDoubleClick={this.handledbClick}
138 onClick={this.changeState}>
139 {input}
140 <label className={clsPrefix+'-label'}>{children}</label>
141 </label>
142 );
143 }
144}
145
146Checkbox.propTypes = propTypes;
147Checkbox.defaultProps = defaultProps;
148
149export default Checkbox;