index.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import React, { PureComponent } from 'react';
  2. import PropTypes from 'prop-types';
  3. import { Select, Spin } from 'antd';
  4. export default class RBRemoteSelect extends PureComponent {
  5. static defaultProps = {
  6. placeholder: '请输入检索内容并根据检索结果进行选择',
  7. };
  8. static propTypes = {
  9. dataSource: PropTypes.array.isRequired,
  10. placeholder: PropTypes.string,
  11. };
  12. handleOnChange = (value) => {
  13. if (this.props.onChange) {
  14. this.props.onChange(value);
  15. }
  16. }
  17. lastTimeStamp = 0;
  18. handleOnSearch = (value) => {
  19. const eventTimeStamp = new Date().getTime();
  20. this.lastTimeStamp = eventTimeStamp;
  21. // 800ms后比较时间时间戳与上次事件的时间戳是否相等
  22. // 相等说明800ms未进行赋值,则触发搜索; 不相等说明还在继续输入,不触发搜索
  23. setTimeout(() => {
  24. if (this.lastTimeStamp === eventTimeStamp) {
  25. this.props.onSearch(value);
  26. this.lastTimeStamp = 0;
  27. }
  28. }, 800);
  29. }
  30. render() {
  31. const { value, dataSource, placeholder, fetching } = this.props;
  32. return (
  33. <div>
  34. <Select
  35. mode="multiple"
  36. filterOption={false}
  37. notFoundContent={fetching ? <Spin size="small" /> : null}
  38. value={value}
  39. onSearch={this.handleOnSearch}
  40. onChange={this.handleOnChange}
  41. placeholder={placeholder}
  42. >
  43. {
  44. dataSource.map(
  45. option => (
  46. <Select.Option
  47. key={option.value}
  48. value={option.value}
  49. >
  50. {option.text}
  51. </Select.Option>
  52. )
  53. )
  54. }
  55. </Select>
  56. </div>
  57. );
  58. }
  59. }