Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | 4x 4x | import React, { useEffect, useRef } from "react"; import classNames from "classnames"; import { DateChangeContext } from "../calendar/DateProps"; import { useConfig } from "../_util/config-context"; import { List } from "../list"; const SCROLL_OFFSET = 80; const SCROLL_DURATION = 120; export interface SelectProps { /** * 当前选择的值 */ value: number; /** * 起始值 */ from?: number; /** * 结束值 */ to: number; /** * 步长 */ step?: number; /** * 禁选范围 */ disabledValues?: number[]; /** * 变化回调 */ onChange: (value: number, context: DateChangeContext) => void; } /** * 滚动到指定元素 */ function scrollTo(element: HTMLElement, to: number, duration: number): void { if (duration <= 0) { element.scrollTop = to; return; } const difference = to - element.scrollTop; const perTick = (difference / duration) * 10; requestAnimationFrame(() => { element.scrollTop += perTick; if (element.scrollTop === to) return; scrollTo(element, to, duration - 10); }); } export function TimeSelect({ value, from = 0, to, step = 1, disabledValues = [], onChange = () => null, }: SelectProps) { const { classPrefix } = useConfig(); const selectRef = useRef(null); useEffect(() => { scrollToSelected(0); }, []); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { scrollToSelected(SCROLL_DURATION); }, [value, from, to, step]); // eslint-disable-line react-hooks/exhaustive-deps /** * 滚动到当前选择元素 */ function scrollToSelected(duration: number): void { const element = selectRef.current; const index = Math.floor(value / step); const topOption = element.children[index] as HTMLElement; const to = topOption.offsetTop - element.offsetTop - SCROLL_OFFSET; scrollTo(element, to, duration); } /** * 根据范围生成列表 */ function genRangeList(): number[] { return Array(Math.floor((to - from + 1) / step)) .fill(0) .map((_, i) => i * step + from); } function handleSelect(event: React.MouseEvent, value: number): void { event.stopPropagation(); onChange(value, { event }); } return ( <List ref={selectRef} type="option" className={`${classPrefix}-list--calendar-time`} > {genRangeList().map(item => { const disabled = disabledValues.includes(item); return ( <List.Item key={item} className={classNames({ "is-disabled": disabled, "is-selected": !disabled && item === value, })} onClick={e => !disabled && handleSelect(e, item)} > <div className={`${classPrefix}-list__item`}> {item > 9 ? `${item}` : `0${item}`} </div> </List.Item> ); })} </List> ); } |