65 lines
2.4 KiB
React
65 lines
2.4 KiB
React
import React, { useState, useRef, useEffect } from 'react';
|
|
import './AutoComplete.css';
|
|
|
|
const OPTIONS = ['北京', '上海', '广州', '深圳', '杭州', '成都', '重庆', '武汉', '西安', '南京', '苏州', '天津'];
|
|
|
|
export default function AutoComplete({ modelValue = '', options = OPTIONS, placeholder = '输入关键字…', onChange, onSelect }) {
|
|
const [open, setOpen] = useState(false);
|
|
const [active, setActive] = useState(-1);
|
|
const [list, setList] = useState([]);
|
|
const root = useRef(null);
|
|
|
|
useEffect(() => {
|
|
const onDoc = (e) => { if (root.current && !root.current.contains(e.target)) setOpen(false); };
|
|
document.addEventListener('click', onDoc);
|
|
return () => document.removeEventListener('click', onDoc);
|
|
}, []);
|
|
|
|
const onInput = (e) => {
|
|
const q = e.target.value;
|
|
if (onChange) onChange(q);
|
|
setActive(-1);
|
|
setList(q ? options.filter((d) => d.indexOf(q) >= 0) : []);
|
|
setOpen(true);
|
|
};
|
|
const highlight = (it) => {
|
|
const q = modelValue.trim();
|
|
if (!q) return it;
|
|
return it.replace(new RegExp('(' + q.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ')', 'g'), '<mark>$1</mark>');
|
|
};
|
|
const move = (d) => { setOpen(true); setActive((a) => Math.max(-1, Math.min(list.length - 1, a + d))); };
|
|
const choose = (i) => { if (onChange) onChange(list[i]); if (onSelect) onSelect(list[i]); setOpen(false); };
|
|
|
|
return (
|
|
<div className="aa-autocomplete" ref={root}>
|
|
<input
|
|
className="aa-autocomplete-input"
|
|
value={modelValue}
|
|
placeholder={placeholder}
|
|
onChange={onInput}
|
|
onKeyDown={(e) => {
|
|
if (e.key === 'ArrowDown') { e.preventDefault(); move(1); }
|
|
else if (e.key === 'ArrowUp') { e.preventDefault(); move(-1); }
|
|
else if (e.key === 'Enter' && active >= 0) choose(active);
|
|
else if (e.key === 'Escape') setOpen(false);
|
|
}}
|
|
/>
|
|
{open && list.length > 0 && (
|
|
<div className="aa-autocomplete-pop">
|
|
{list.map((it, i) => (
|
|
<div
|
|
key={i}
|
|
className={'aa-autocomplete-item' + (i === active ? ' is-active' : '')}
|
|
onClick={() => choose(i)}
|
|
dangerouslySetInnerHTML={{ __html: highlight(it) }}
|
|
/>
|
|
))}
|
|
</div>
|
|
)}
|
|
{open && modelValue && list.length === 0 && (
|
|
<div className="aa-autocomplete-pop"><div className="aa-autocomplete-empty">无匹配结果</div></div>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|