zarm-web
Version:
基于 React 的桌面端UI库
80 lines (71 loc) • 1.76 kB
JavaScript
import React, { Component } from 'react';
import ActivityIndicator from 'zarm/lib/activity-indicator';
import classnames from 'classnames';
class Switch extends Component {
constructor(props) {
super(props);
this.state = {
checked: props.checked || props.defaultChecked
};
}
static getDerivedStateFromProps(nextProps, prevState) {
if ('checked' in nextProps && nextProps.checked !== prevState.checked) {
return {
checked: nextProps.checked
};
}
return null;
}
_onClick() {
const {
onChange
} = this.props;
const {
checked
} = this.state;
const newChecked = !checked;
if (!('checked' in this.props)) {
this.setState({
checked: newChecked
});
}
typeof onChange === 'function' && onChange(newChecked);
}
render() {
const {
size,
disabled,
className,
prefixCls,
loading,
style
} = this.props;
const {
checked
} = this.state;
const cls = classnames(prefixCls, className, {
[`${prefixCls}--checked`]: checked,
[`${prefixCls}--disabled`]: disabled || loading,
[`${prefixCls}--loading`]: loading,
[`${prefixCls}--${size}`]: size === 'sm'
});
return React.createElement("button", {
type: "button",
role: "switch",
"aria-checked": checked,
className: cls,
style: style,
onClick: () => !disabled && !loading && this._onClick()
}, loading && React.createElement(ActivityIndicator, {
prefixCls: "zw-activity-indicator"
}));
}
}
Switch.displayName = 'Switch';
Switch.defaultProps = {
prefixCls: 'zw-switch',
loading: false,
size: 'md',
defaultChecked: false
};
export default Switch;