/
List.jsx
64 lines (56 loc) · 1.46 KB
/
List.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import React, { PropTypes } from 'react';
import assign from 'object-assign';
function noop() {
}
class List extends React.Component {
constructor() {
super(...arguments);
this.state = {
defaultValue: this.props.defaultValue,
};
[
'listOnClick',
].forEach((method) => this[method] = this[method].bind(this));
}
componentWillReceiveProps(nextProps) {
const { defaultValue } = nextProps;
this.setState({ defaultValue });
}
listOnClick(value, e) {
this.props.onChange(value, e);
this.setState({
defaultValue: value,
});
}
render() {
const childrenToRender = React.Children.toArray(this.props.children).map(item => {
if (!item.props.value) {
return item;
}
const props = assign({}, item.props);
props.className = (props.className || '').replace('active', '');
if (item.props.value === this.state.defaultValue) {
props.className = `${props.className} active`.trim();
}
props.onClick = this.listOnClick.bind(this, item.props.value);
return React.cloneElement(item, props);
});
return React.createElement(
this.props.component,
this.props,
childrenToRender
);
}
}
List.propTypes = {
children: PropTypes.any,
className: PropTypes.string,
component: PropTypes.any,
defaultValue: PropTypes.string,
onChange: PropTypes.func,
};
List.defaultProps = {
component: 'ul',
onChange: noop,
};
export default List;