UNPKG

3.25 kBJavaScriptView Raw
1import _extends from 'babel-runtime/helpers/extends';
2import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
3import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
4import _inherits from 'babel-runtime/helpers/inherits';
5
6var _class, _temp;
7
8import React, { Component } from 'react';
9import PropTypes from 'prop-types';
10import classNames from 'classnames';
11import { polyfill } from 'react-lifecycles-compat';
12import { obj, func } from '../util';
13import Tag from './tag';
14
15var noop = func.noop,
16 bindCtx = func.bindCtx;
17
18/**
19 * Tag.Selectable
20 */
21
22var Selectable = (_temp = _class = function (_Component) {
23 _inherits(Selectable, _Component);
24
25 function Selectable(props) {
26 _classCallCheck(this, Selectable);
27
28 var _this = _possibleConstructorReturn(this, _Component.call(this, props));
29
30 _this.state = {
31 checked: 'checked' in props ? props.checked : props.defaultChecked || false
32 };
33
34 bindCtx(_this, ['handleClick']);
35 return _this;
36 }
37
38 Selectable.getDerivedStateFromProps = function getDerivedStateFromProps(props, state) {
39 if (props.checked !== undefined && props.checked !== state.checked) {
40 return {
41 checked: props.checked
42 };
43 }
44
45 return null;
46 };
47
48 Selectable.prototype.handleClick = function handleClick(e) {
49 e && e.preventDefault();
50 // IE9 不支持 pointer-events,还是可能会触发 click 事件
51 if (this.props.disabled) {
52 return false;
53 }
54
55 var checked = this.state.checked;
56
57
58 this.setState({
59 checked: !checked
60 });
61
62 this.props.onChange(!checked, e);
63 };
64
65 Selectable.prototype.render = function render() {
66 var attrFilterTarget = ['checked', 'defaultChecked', 'onChange', 'className',
67 // 防止这些额外的参数影响 tag 的类型
68 '_shape', 'closable'];
69
70 var others = obj.pickOthers(attrFilterTarget, this.props);
71 var isChecked = 'checked' in this.props ? this.props.checked : this.state.checked;
72 var clazz = classNames(this.props.className, {
73 checked: isChecked
74 });
75 return React.createElement(Tag, _extends({}, others, {
76 role: 'checkbox',
77 _shape: 'checkable',
78 'aria-checked': isChecked,
79 className: clazz,
80 onClick: this.handleClick
81 }));
82 };
83
84 return Selectable;
85}(Component), _class.propTypes = {
86 /**
87 * 标签是否被选中,受控用法
88 * tag checked or not, a controlled way
89 */
90 checked: PropTypes.bool,
91 /**
92 * 标签是否默认被选中,非受控用法
93 * tag checked or not by default, a uncontrolled way
94 */
95 defaultChecked: PropTypes.bool,
96 /**
97 * 选中状态变化时触发的事件
98 * @param {Boolean} checked 是否选中
99 * @param {Event} e Dom 事件对象
100 */
101 onChange: PropTypes.func,
102 /**
103 * 标签是否被禁用
104 */
105 disabled: PropTypes.bool,
106 className: PropTypes.any
107}, _class.defaultProps = {
108 onChange: noop
109}, _temp);
110Selectable.displayName = 'Selectable';
111
112
113export default polyfill(Selectable);
\No newline at end of file