autoCompleteSearch.jsx 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import React,{Component} from "react";
  2. import {AutoComplete, message, Select,Spin} from "antd";
  3. import $ from "jquery/src/ajax";
  4. class AutoCompleteSearch extends Component{
  5. constructor(props) {
  6. super(props);
  7. this.state={
  8. contactsOption:[],
  9. autoCompleteSearchLoading:false,
  10. searchValue:props.config.searchValue
  11. }
  12. this.onSelect = this.onSelect.bind(this);
  13. this.onSearch = this.onSearch.bind(this);
  14. }
  15. onSelect(value,option){
  16. let arr = this.state.contactsOption.filter(v=>v.value === value);
  17. this.setState({
  18. searchValue:arr[0]['value']
  19. })
  20. this.props.onSelect(value,option.props.children)
  21. }
  22. onSearch(value){
  23. if(this.state.autoCompleteSearchLoading){
  24. this.ajax && this.ajax.abort();
  25. }
  26. this.setState({
  27. autoCompleteSearchLoading: true,
  28. searchValue: value
  29. });
  30. let data = {};
  31. data[this.props.config.search] = value
  32. this.ajax = $.ajax({
  33. method: "get",
  34. dataType: "json",
  35. crossDomain: false,
  36. url: globalConfig.context + this.props.config.api,
  37. data,
  38. success: function (data) {
  39. let theArr = [];
  40. if (data.error && data.error.length === 0) {
  41. for(let i=0;i<data.data.length;i++){
  42. let theData = data.data[i];
  43. theArr.push(
  44. {
  45. value:theData.id,
  46. label:theData.name
  47. }
  48. );
  49. };
  50. this.setState({
  51. contactsOption: theArr,
  52. });
  53. }else{
  54. message.warning(data.error[0].message);
  55. }
  56. }.bind(this),
  57. }).always(function () {
  58. this.setState({
  59. autoCompleteSearchLoading: false
  60. });
  61. }.bind(this));
  62. }
  63. render() {
  64. const customerOptions = this.state.contactsOption.map((group) => (
  65. <Select.Option key={group.label} value={group.value}>
  66. {group.label}
  67. </Select.Option>
  68. ));
  69. return (
  70. <Spin spinning={this.state.autoCompleteSearchLoading}>
  71. <AutoComplete
  72. value={this.props.value ? this.state.searchValue : ''}
  73. dataSource={customerOptions}
  74. style={{ width: 200 }}
  75. onSelect={this.onSelect}
  76. onSearch={this.onSearch}
  77. placeholder={this.props.config.placeholder}
  78. />
  79. </Spin>
  80. )
  81. }
  82. }
  83. export default AutoCompleteSearch;