1 import React, { PropTypes } from 'react';
2 import ReactDom from 'react-dom';
3 import classnames from 'classnames';
5 const scrollTo = (element, to, duration) => {
6 const requestAnimationFrame = window.requestAnimationFrame ||
7 function requestAnimationFrameTimeout() {
8 return setTimeout(arguments[0], 10);
10 // jump to target if duration zero
12 element.scrollTop = to;
15 const difference = to - element.scrollTop;
16 const perTick = difference / duration * 10;
18 requestAnimationFrame(() => {
19 element.scrollTop = element.scrollTop + perTick;
20 if (element.scrollTop === to) return;
21 scrollTo(element, to, duration - 10);
25 const Select = React.createClass({
27 prefixCls: PropTypes.string,
28 options: PropTypes.array,
29 selectedIndex: PropTypes.number,
30 type: PropTypes.string,
31 onSelect: PropTypes.func,
32 onMouseEnter: PropTypes.func,
36 // jump to selected option
37 this.scrollToSelected(0);
40 componentDidUpdate(prevProps) {
41 // smooth scroll to selected option
42 if (prevProps.selectedIndex !== this.props.selectedIndex) {
43 this.scrollToSelected(120);
48 const { onSelect, type } = this.props;
49 onSelect(type, value);
53 const { options, selectedIndex, prefixCls } = this.props;
54 return options.map((item, index) => {
55 const cls = classnames({
56 [`${prefixCls}-select-option-selected`]: selectedIndex === index,
57 [`${prefixCls}-select-option-disabled`]: item.disabled,
61 onclick = this.onSelect.bind(this, +item.value);
67 disabled={item.disabled}
74 scrollToSelected(duration) {
75 // move to selected item
76 const select = ReactDom.findDOMNode(this);
77 const list = ReactDom.findDOMNode(this.refs.list);
78 let index = this.props.selectedIndex;
82 const topOption = list.children[index];
83 const to = topOption.offsetTop;
84 scrollTo(select, to, duration);
88 if (this.props.options.length === 0) {
92 const { prefixCls } = this.props;
96 className={`${prefixCls}-select`}
97 onMouseEnter={this.props.onMouseEnter}
99 <ul ref="list">{this.getOptions()}</ul>
105 export default Select;