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,
42 // jump to selected option
43 this.scrollToSelected(0);
46 componentDidUpdate(prevProps) {
47 // smooth scroll to selected option
48 if (prevProps.selectedIndex !== this.props.selectedIndex) {
49 this.scrollToSelected(120);
54 const { onSelect, type } = this.props;
55 onSelect(type, value);
59 const { options, selectedIndex, prefixCls } = this.props;
60 return options.map((item, index) => {
61 const cls = classnames({
62 [`${prefixCls}-select-option-selected`]: selectedIndex === index,
63 [`${prefixCls}-select-option-disabled`]: item.disabled,
67 onclick = this.onSelect.bind(this, item.value);
73 disabled={item.disabled}
80 scrollToSelected(duration) {
81 // move to selected item
82 const select = ReactDom.findDOMNode(this);
83 const list = ReactDom.findDOMNode(this.refs.list);
87 let index = this.props.selectedIndex;
91 const topOption = list.children[index];
92 const to = topOption.offsetTop;
93 scrollTo(select, to, duration);
97 this.setState({ active: true });
98 this.props.onMouseEnter(e);
102 this.setState({ active: false });
106 if (this.props.options.length === 0) {
110 const { prefixCls } = this.props;
111 const cls = classnames({
112 [`${prefixCls}-select`]: 1,
113 [`${prefixCls}-select-active`]: this.state.active,
119 onMouseEnter={this.handleMouseEnter}
120 onMouseLeave={this.handleMouseLeave}
122 <ul ref="list">{this.getOptions()}</ul>
128 export default Select;