UNPKG

2.35 kBJavaScriptView Raw
1import classNames from 'classnames';
2import React, { cloneElement } from 'react';
3import PropTypes from 'prop-types';
4import { createChainedFunction } from 'tinper-bee-core';
5
6
7const propTypes = {
8 //是否是手风琴效果
9 accordion: PropTypes.bool,
10 //激活的项
11 activeKey: PropTypes.any,
12 //默认的激活的项
13 defaultActiveKey: PropTypes.any,
14 //选中函数
15 onSelect: PropTypes.func,
16 role: PropTypes.string,
17};
18
19const defaultProps = {
20 accordion: false,
21 clsPrefix: 'u-panel-group'
22};
23
24// TODO: Use uncontrollable.
25
26class PanelGroup extends React.Component {
27 constructor(props, context) {
28 super(props, context);
29
30 this.handleSelect = this.handleSelect.bind(this);
31
32 this.state = {
33 activeKey: props.defaultActiveKey,
34 };
35 }
36
37 handleSelect(key, e) {
38 e.preventDefault();
39
40 if (this.props.onSelect) {
41 this.props.onSelect(key, e);
42 }
43
44 if (this.state.activeKey === key) {
45 key = null;
46 }
47
48 this.setState({ activeKey: key });
49 }
50
51 render() {
52 const {
53 accordion,
54 activeKey: propsActiveKey,
55 className,
56 children,
57 defaultActiveKey,
58 onSelect,
59 style,
60 clsPrefix,
61 ...others
62 } = this.props;
63
64
65 let activeKey;
66 if (accordion) {
67 activeKey = propsActiveKey != null ?
68 propsActiveKey : this.state.activeKey;
69 others.role = others.role || 'tablist';
70 }
71
72 const classes = {};
73 classes[`${clsPrefix}`] = true;
74
75 return (
76 <div
77 {...others}
78 className={classNames(className, classes)}
79 >
80 {React.Children.map(children, child => {
81 if (!React.isValidElement(child)) {
82 return child;
83 }
84 const childProps = {
85 style: child.props.style,
86 };
87
88 if (accordion) {
89 Object.assign(childProps, {
90 headerRole: 'tab',
91 panelRole: 'tabpanel',
92 collapsible: true,
93 expanded: child.props.eventKey === activeKey,
94 onSelect: createChainedFunction(
95 this.handleSelect, child.props.onSelect
96 )
97 });
98 }
99
100 return cloneElement(child, childProps);
101 })}
102 </div>
103 );
104 }
105}
106
107PanelGroup.propTypes = propTypes;
108PanelGroup.defaultProps = defaultProps;
109
110export default PanelGroup;