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