index.jsx 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import React, { useState, useEffect, useCallback, useRef } from 'react';
  2. import { useDebounceFn } from 'ahooks';
  3. import { Input } from 'antd';
  4. import Icon from '@/tenants-ui/Icon';
  5. import cx from 'classnames';
  6. import styles from './index.less';
  7. export default ({ placeholder, onSearch, onCancel }) => {
  8. const ref = useRef();
  9. const [focus, setFocus] = useState(false);
  10. const [searchValue, setSearchValue] = useState('');
  11. const { run } = useDebounceFn(
  12. (val) => {
  13. onSearch(val);
  14. },
  15. {
  16. wait: 500,
  17. },
  18. );
  19. const handleClose = useCallback((e) => {
  20. if (e.keyCode === 27) {
  21. setFocus(false);
  22. setSearchValue('');
  23. onCancel();
  24. ref.current.blur();
  25. }
  26. }, []);
  27. useEffect(() => {
  28. document.addEventListener('keyup', handleClose);
  29. return () => {
  30. document.removeEventListener('keyup', handleClose);
  31. };
  32. }, []);
  33. return (
  34. <div
  35. className={cx(styles.searchInput, {
  36. [styles.focus]: focus,
  37. })}
  38. >
  39. <Icon type="search" style={{ color: '#C4C4C4' }} />
  40. <div className={styles.input}>
  41. <Input
  42. style={{ width: '100%' }}
  43. ref={ref}
  44. size="large"
  45. bordered={false}
  46. onFocus={() => setFocus(true)}
  47. onBlur={() => {
  48. if (!searchValue) {
  49. setFocus(false);
  50. }
  51. }}
  52. value={searchValue}
  53. placeholder={placeholder}
  54. onChange={(e) => {
  55. const val = e.target.value;
  56. setSearchValue(val);
  57. //run(val);
  58. onSearch(val);
  59. }}
  60. />
  61. </div>
  62. <div className={styles.cancel} onClick={() => handleClose({ keyCode: 27 })}>
  63. <Icon type="backward" />
  64. 取消搜索
  65. </div>
  66. </div>
  67. );
  68. };