1 import React, { Component } from 'react';
2 import PropTypes from 'prop-types';
3 import ReactDom from 'react-dom';
4 import classnames from 'classnames';
6 const scrollTo = (element, to, duration) => {
7 const requestAnimationFrame = window.requestAnimationFrame ||
8 function requestAnimationFrameTimeout() {
9 return setTimeout(arguments[0], 10);
11 // jump to target if duration zero
13 element.scrollTop = to;
16 const difference = to - element.scrollTop;
17 const perTick = difference / duration * 10;
19 requestAnimationFrame(() => {
20 element.scrollTop = element.scrollTop + perTick;
21 if (element.scrollTop === to) return;
22 scrollTo(element, to, duration - 10);
26 class Select extends Component {
28 prefixCls: PropTypes.string,
29 options: PropTypes.array,
30 selectedIndex: PropTypes.number,
31 type: PropTypes.string,
32 onSelect: PropTypes.func,
33 onMouseEnter: PropTypes.func,
41 // jump to selected option
42 this.scrollToSelected(0);
45 componentDidUpdate(prevProps) {
46 // smooth scroll to selected option
47 if (prevProps.selectedIndex !== this.props.selectedIndex) {
48 this.scrollToSelected(120);
52 onSelect = (value) => {
53 const { onSelect, type } = this.props;
54 onSelect(type, value);
58 const { options, selectedIndex, prefixCls } = this.props;
59 return options.map((item, index) => {
60 const cls = classnames({
61 [`${prefixCls}-select-option-selected`]: selectedIndex === index,
62 [`${prefixCls}-select-option-disabled`]: item.disabled,
66 onclick = this.onSelect.bind(this, item.value);
72 disabled={item.disabled}
79 scrollToSelected(duration) {
80 // move to selected item
81 const select = ReactDom.findDOMNode(this);
82 const list = ReactDom.findDOMNode(this.refs.list);
86 let index = this.props.selectedIndex;
90 const topOption = list.children[index];
91 const to = topOption.offsetTop;
92 scrollTo(select, to, duration);
95 handleMouseEnter = (e) => {
96 this.setState({ active: true });
97 this.props.onMouseEnter(e);
100 handleMouseLeave = () => {
101 this.setState({ active: false });
105 if (this.props.options.length === 0) {
109 const { prefixCls } = this.props;
110 const cls = classnames({
111 [`${prefixCls}-select`]: 1,
112 [`${prefixCls}-select-active`]: this.state.active,
118 onMouseEnter={this.handleMouseEnter}
119 onMouseLeave={this.handleMouseLeave}
121 <ul ref="list">{this.getOptions()}</ul>
127 export default Select;