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