index.js 2.1 KB
Newer Older
1
import React, { PureComponent } from 'react';
afc163's avatar
afc163 committed
2
import PropTypes from 'prop-types';
3 4 5 6 7 8 9
import { Input, Icon, AutoComplete } from 'antd';
import classNames from 'classnames';
import styles from './index.less';

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