UNPKG

3.19 kBJavaScriptView Raw
1import React, { Component } from "react";
2import ReactDOM from "react-dom";
3import classnames from "classnames";
4import PropTypes from "prop-types";
5
6const propTypes = {
7 clsPrefix: PropTypes.string,
8 disabled: PropTypes.bool,
9 checkedChildren: PropTypes.any,
10 unCheckedChildren: PropTypes.any,
11 onChangeHandler: PropTypes.func,
12 onChange: PropTypes.func
13};
14const defaultProps = {
15 clsPrefix: "u-switch",
16 checkedChildren: null,
17 unCheckedChildren: null,
18 defaultChecked: false,
19 size: "",
20 disabled: false,
21 onChangeHandler: function() {},
22 onChange: function() {}
23};
24class Switch extends Component {
25 constructor(props) {
26 super(props);
27 let checked = false;
28 if ('checked' in props) {
29 checked = !!props.checked;
30 } else if('defaultValue' in props) {
31 checked = !!props.defaultValue;
32 } else{
33 checked = !!props.defaultChecked;
34 }
35 this.state = { checked };
36 }
37 componentWillReceiveProps(nextProps, nextState) {
38 if ("checked" in nextProps) {
39 this.setState({ checked: !!nextProps.checked });
40 }
41 }
42 setChecked=(checked)=>{
43 if (this.props.disabled) {
44 return;
45 }
46 if (!('checked' in this.props)) {
47 this.setState({
48 checked,
49 });
50 }
51 this.props.onChangeHandler(checked);
52 this.props.onChange(checked);
53 }
54 //点击switch改变状态
55 clickHandler = () => {
56 const checked = !this.state.checked;
57 this.setChecked(checked);
58 };
59 handleKeyDown = (e) => {
60 if (e.keyCode === 37) { // Left
61 this.setChecked(false);
62 } else if (e.keyCode === 39) { // Right
63 this.setChecked(true);
64 } else if (e.keyCode === 32 || e.keyCode === 13) { // Space, Enter
65 this.clickHandler();
66 }
67 }
68 // Handle auto focus when click switch in Chrome
69 handleMouseUp = (e) => {
70 if (this.node) {
71 this.node.blur();
72 }
73 if (this.props.onMouseUp) {
74 this.props.onMouseUp(e);
75 }
76 }
77 saveNode = (node) => {
78 this.node = node;
79 }
80 render() {
81 const {
82 checkedChildren,
83 unCheckedChildren,
84 onChangeHandler,
85 size,
86 className,
87 clsPrefix,
88 disabled,
89 colors,
90 ...others
91 } = this.props;
92 //获取checked
93 const checked = this.state.checked;
94 let classes = {
95 "is-checked": checked
96 };
97 if (size) {
98 classes[`${clsPrefix}-${size}`] = true;
99 }
100 if (colors) {
101 classes[`${clsPrefix}-${colors}`] = true;
102 }
103 classes[[`${clsPrefix}-disabled`]] = disabled;
104
105 let classNames = classnames(clsPrefix, classes);
106
107 return (
108 <span
109 {...others}
110 ref={this.saveNode}
111 onClick={this.clickHandler}
112 onKeyDown={this.handleKeyDown}
113 onMouseUp={this.handleMouseUp}
114 className={classnames(className, classNames)}
115 tabIndex={disabled ? -1 : 0}
116 >
117 <span className={`${clsPrefix}-inner`}>
118 {checked ? checkedChildren : unCheckedChildren}
119 </span>
120 </span>
121 );
122 }
123}
124Switch.propTypes = propTypes;
125Switch.defaultProps = defaultProps;
126export default Switch;