1 import React, {PropTypes} from 'react';
2 import ReactDom from 'react-dom';
3 import classnames from 'classnames';
5 const scrollTo = (element, to, duration) => {
6 // jump to target if duration zero
8 element.scrollTop = to;
11 const difference = to - element.scrollTop;
12 const perTick = difference / duration * 10;
15 element.scrollTop = element.scrollTop + perTick;
16 if (element.scrollTop === to) return;
17 scrollTo(element, to, duration - 10);
21 const Select = React.createClass({
23 prefixCls: PropTypes.string,
24 options: PropTypes.array,
25 gregorianCalendarLocale: PropTypes.object,
26 selectedIndex: PropTypes.number,
27 type: PropTypes.string,
28 onSelect: PropTypes.func,
32 // jump to selected option
33 this.scrollToSelected(0);
36 componentDidUpdate() {
37 // smooth scroll to selected option
38 this.scrollToSelected(200);
42 const { onSelect, type } = this.props;
43 onSelect(type, value);
47 const { options, selectedIndex, prefixCls } = this.props;
48 return options.map((item, index) => {
49 const selected = selectedIndex === index;
50 const cls = classnames({
51 [`${prefixCls}-select-option-selected`]: selected,
53 return <li className={cls} key={index} onClick={this.onSelect.bind(this, +item)}>{item}</li>;
57 scrollToSelected(duration) {
58 // move to selected item
59 const select = ReactDom.findDOMNode(this);
60 const list = ReactDom.findDOMNode(this.refs.list);
61 let index = this.props.selectedIndex - 2;
65 const topOption = list.children[index];
66 const to = topOption.offsetTop - select.offsetTop;
67 scrollTo(select, to, duration);
71 if (this.props.options.length === 0) {
75 const { prefixCls } = this.props;
78 <div className={`${prefixCls}-select`}>
79 <ul ref="list">{this.getOptions()}</ul>
85 export default Select;