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'), '$1'); }; 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 (