]>
Commit | Line | Data |
---|---|---|
02de449a | 1 | import React, {PropTypes} from 'react'; |
2 | import ReactDom from 'react-dom'; | |
3 | import classnames from 'classnames'; | |
4 | ||
5 | const scrollTo = (element, to, duration) => { | |
6 | // jump to target if duration zero | |
7 | if (duration <= 0) { | |
8 | element.scrollTop = to; | |
9 | return; | |
10 | } | |
11 | const difference = to - element.scrollTop; | |
12 | const perTick = difference / duration * 10; | |
13 | ||
14 | setTimeout(() => { | |
15 | element.scrollTop = element.scrollTop + perTick; | |
16 | if (element.scrollTop === to) return; | |
17 | scrollTo(element, to, duration - 10); | |
18 | }, 10); | |
19 | }; | |
20 | ||
21 | const Select = React.createClass({ | |
22 | propTypes: { | |
23 | prefixCls: PropTypes.string, | |
24 | options: PropTypes.array, | |
8133e8cf | 25 | gregorianCalendarLocale: PropTypes.object, |
02de449a | 26 | selectedIndex: PropTypes.number, |
27 | type: PropTypes.string, | |
28 | onSelect: PropTypes.func, | |
29 | }, | |
30 | ||
31 | componentDidMount() { | |
32 | // jump to selected option | |
33 | this.scrollToSelected(0); | |
34 | }, | |
35 | ||
36 | componentDidUpdate() { | |
37 | // smooth scroll to selected option | |
a9fbba23 | 38 | this.scrollToSelected(120); |
02de449a | 39 | }, |
40 | ||
8133e8cf | 41 | onSelect(value) { |
02de449a | 42 | const { onSelect, type } = this.props; |
02de449a | 43 | onSelect(type, value); |
44 | }, | |
45 | ||
46 | getOptions() { | |
8133e8cf | 47 | const { options, selectedIndex, prefixCls } = this.props; |
02de449a | 48 | return options.map((item, index) => { |
8133e8cf | 49 | const selected = selectedIndex === index; |
50 | const cls = classnames({ | |
51 | [`${prefixCls}-select-option-selected`]: selected, | |
52 | }); | |
53 | return <li className={cls} key={index} onClick={this.onSelect.bind(this, +item)}>{item}</li>; | |
02de449a | 54 | }); |
55 | }, | |
56 | ||
57 | scrollToSelected(duration) { | |
58 | // move to selected item | |
59 | const select = ReactDom.findDOMNode(this); | |
60 | const list = ReactDom.findDOMNode(this.refs.list); | |
41bec13a | 61 | let index = this.props.selectedIndex - 1; |
02de449a | 62 | if (index < 0) { |
63 | index = 0; | |
64 | } | |
65 | const topOption = list.children[index]; | |
66 | const to = topOption.offsetTop - select.offsetTop; | |
67 | scrollTo(select, to, duration); | |
68 | }, | |
69 | ||
70 | render() { | |
71 | if (this.props.options.length === 0) { | |
72 | return null; | |
73 | } | |
74 | ||
75 | const { prefixCls } = this.props; | |
76 | ||
77 | return ( | |
78 | <div className={`${prefixCls}-select`}> | |
79 | <ul ref="list">{this.getOptions()}</ul> | |
80 | </div> | |
81 | ); | |
82 | }, | |
83 | }); | |
84 | ||
85 | export default Select; |