autoCompleteSearch.jsx 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. onReset(){
  16. this.setState({
  17. searchValue:''
  18. })
  19. }
  20. onSelect(value,option){
  21. let arr = this.state.contactsOption.filter(v=>v.value === value);
  22. this.setState({
  23. searchValue:arr[0]['value']
  24. })
  25. this.props.onSelect(value,option.props.children)
  26. }
  27. onSearch(value){
  28. if(this.state.autoCompleteSearchLoading){
  29. this.ajax && this.ajax.abort();
  30. }
  31. this.setState({
  32. autoCompleteSearchLoading: true,
  33. searchValue: value
  34. });
  35. let data = {};
  36. data[this.props.config.search] = value
  37. this.ajax = $.ajax({
  38. method: "get",
  39. dataType: "json",
  40. crossDomain: false,
  41. url: globalConfig.context + this.props.config.api,
  42. data,
  43. success: function (data) {
  44. let theArr = [];
  45. if (data.error && data.error.length === 0) {
  46. for(let i=0;i<data.data.length;i++){
  47. let theData = data.data[i];
  48. theArr.push(
  49. {
  50. value:theData.id,
  51. label:theData.name
  52. }
  53. );
  54. };
  55. this.setState({
  56. contactsOption: theArr,
  57. });
  58. }else{
  59. message.warning(data.error[0].message);
  60. }
  61. }.bind(this),
  62. }).always(function () {
  63. this.setState({
  64. autoCompleteSearchLoading: false
  65. });
  66. }.bind(this));
  67. }
  68. render() {
  69. const customerOptions = this.state.contactsOption.map((group) => (
  70. <Select.Option key={group.label} value={group.value}>
  71. {group.label}
  72. </Select.Option>
  73. ));
  74. return (
  75. <Spin spinning={this.state.autoCompleteSearchLoading}>
  76. <AutoComplete
  77. value={this.state.searchValue}
  78. dataSource={customerOptions}
  79. style={{ width: 200 }}
  80. onSelect={this.onSelect}
  81. onSearch={this.onSearch}
  82. placeholder={this.props.config.placeholder}
  83. />
  84. </Spin>
  85. )
  86. }
  87. }
  88. export default AutoCompleteSearch;