import { useRouter } from 'next/router' import { useImperativeHandle, useRef, useState } from 'react' let lock = false const SearchInput = ({ keyword, cRef, className }) => { const [onLoading, setLoadingState] = useState(false) const router = useRouter() const searchInputRef = useRef() useImperativeHandle(cRef, () => { return { focus: () => { searchInputRef?.current?.focus() } } }) const handleSearch = () => { const key = searchInputRef.current.value if (key && key !== '') { setLoadingState(true) location.href = '/search/' + key } else { router.push({ pathname: '/' }).then(r => { }) } } const handleKeyUp = (e) => { if (e.keyCode === 13) { // 回车 handleSearch(searchInputRef.current.value) } else if (e.keyCode === 27) { // ESC cleanSearch() } } const cleanSearch = () => { searchInputRef.current.value = '' } const [showClean, setShowClean] = useState(false) const updateSearchKey = (val) => { if (lock) { return } searchInputRef.current.value = val if (val) { setShowClean(true) } else { setShowClean(false) } } function lockSearchInput() { lock = true } function unLockSearchInput() { lock = false } return
updateSearchKey(e.target.value)} defaultValue={keyword} />
{(showClean &&
)}
} export default SearchInput