index.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import React, { PureComponent } from 'react';
  2. import PropTypes from 'prop-types';
  3. import { Input, Icon, AutoComplete } from 'antd';
  4. import classNames from 'classnames';
  5. import styles from './index.less';
  6. export default class HeaderSearch extends PureComponent {
  7. static defaultProps = {
  8. defaultActiveFirstOption: false,
  9. onPressEnter: () => {},
  10. onSearch: () => {},
  11. className: '',
  12. placeholder: '',
  13. dataSource: [],
  14. };
  15. static propTypes = {
  16. className: PropTypes.string,
  17. placeholder: PropTypes.string,
  18. onSearch: PropTypes.func,
  19. onPressEnter: PropTypes.func,
  20. defaultActiveFirstOption: PropTypes.bool,
  21. dataSource: PropTypes.array,
  22. };
  23. state = {
  24. searchMode: false,
  25. value: '',
  26. };
  27. componentWillUnmount() {
  28. clearTimeout(this.timeout);
  29. }
  30. onKeyDown = e => {
  31. if (e.key === 'Enter') {
  32. this.timeout = setTimeout(() => {
  33. this.props.onPressEnter(this.state.value); // Fix duplicate onPressEnter
  34. }, 0);
  35. }
  36. };
  37. onChange = value => {
  38. this.setState({ value });
  39. if (this.props.onChange) {
  40. this.props.onChange();
  41. }
  42. };
  43. enterSearchMode = () => {
  44. this.setState({ searchMode: true }, () => {
  45. if (this.state.searchMode) {
  46. this.input.focus();
  47. }
  48. });
  49. };
  50. leaveSearchMode = () => {
  51. this.setState({
  52. searchMode: false,
  53. value: '',
  54. });
  55. };
  56. render() {
  57. const { className, placeholder, ...restProps } = this.props;
  58. const inputClass = classNames(styles.input, {
  59. [styles.show]: this.state.searchMode,
  60. });
  61. return (
  62. <span className={classNames(className, styles.headerSearch)} onClick={this.enterSearchMode}>
  63. <Icon type="search" key="Icon" />
  64. <AutoComplete
  65. key="AutoComplete"
  66. {...restProps}
  67. className={inputClass}
  68. value={this.state.value}
  69. onChange={this.onChange}
  70. >
  71. <Input
  72. placeholder={placeholder}
  73. ref={node => {
  74. this.input = node;
  75. }}
  76. onKeyDown={this.onKeyDown}
  77. onBlur={this.leaveSearchMode}
  78. />
  79. </AutoComplete>
  80. </span>
  81. );
  82. }
  83. }