autoCompleteSearch.jsx 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. if(value == "") {
  36. this.setState({
  37. autoCompleteSearchLoading: false,
  38. })
  39. return
  40. }
  41. let data = {};
  42. data[this.props.config.search] = value
  43. this.ajax = $.ajax({
  44. method: "get",
  45. dataType: "json",
  46. crossDomain: false,
  47. url: globalConfig.context + this.props.config.api,
  48. data,
  49. success: function (data) {
  50. let theArr = [];
  51. if (data.error && data.error.length === 0) {
  52. for(let i=0;i<data.data.length;i++){
  53. let theData = data.data[i];
  54. theArr.push(
  55. {
  56. value:theData.id,
  57. label:theData.name
  58. }
  59. );
  60. };
  61. this.setState({
  62. contactsOption: theArr,
  63. });
  64. }else{
  65. message.warning(data.error[0].message);
  66. }
  67. }.bind(this),
  68. }).always(function () {
  69. this.setState({
  70. autoCompleteSearchLoading: false
  71. });
  72. }.bind(this));
  73. }
  74. render() {
  75. const customerOptions = this.state.contactsOption.map((group) => (
  76. <Select.Option key={group.label} value={group.value}>
  77. {group.label}
  78. </Select.Option>
  79. ));
  80. return (
  81. <Spin spinning={this.state.autoCompleteSearchLoading}>
  82. <AutoComplete
  83. value={this.state.searchValue}
  84. dataSource={customerOptions}
  85. style={{ width: 200 }}
  86. onSelect={this.onSelect}
  87. onSearch={this.onSearch}
  88. placeholder={this.props.config.placeholder}
  89. />
  90. </Spin>
  91. )
  92. }
  93. }
  94. export default AutoCompleteSearch;