index.js 2.3 KB

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