ant-design/components/select/demo/search-box.md
MadCcc 6776bb8916
docs: demo support react18 (#34843)
* docs: update demo

* chore: add script

* test: fix demo test

* docs: convert demos

* chore: move script

* test: remove react-dom import

* chore: update deps

* docs: update riddle js

* test: fix image test

* docs: fix riddle demo
2022-04-03 23:27:45 +08:00

1.8 KiB

order title
9
zh-CN en-US
搜索框 Search Box

zh-CN

搜索和远程数据结合。

en-US

Search with remote data.

import { Select } from 'antd';
import jsonp from 'fetch-jsonp';
import qs from 'qs';

const { Option } = Select;

let timeout;
let currentValue;

function fetch(value, callback) {
  if (timeout) {
    clearTimeout(timeout);
    timeout = null;
  }
  currentValue = value;

  function fake() {
    const str = qs.stringify({
      code: 'utf-8',
      q: value,
    });
    jsonp(`https://suggest.taobao.com/sug?${str}`)
      .then(response => response.json())
      .then(d => {
        if (currentValue === value) {
          const { result } = d;
          const data = [];
          result.forEach(r => {
            data.push({
              value: r[0],
              text: r[0],
            });
          });
          callback(data);
        }
      });
  }

  timeout = setTimeout(fake, 300);
}

class SearchInput extends React.Component {
  state = {
    data: [],
    value: undefined,
  };

  handleSearch = value => {
    if (value) {
      fetch(value, data => this.setState({ data }));
    } else {
      this.setState({ data: [] });
    }
  };

  handleChange = value => {
    this.setState({ value });
  };

  render() {
    const options = this.state.data.map(d => <Option key={d.value}>{d.text}</Option>);
    return (
      <Select
        showSearch
        value={this.state.value}
        placeholder={this.props.placeholder}
        style={this.props.style}
        defaultActiveFirstOption={false}
        showArrow={false}
        filterOption={false}
        onSearch={this.handleSearch}
        onChange={this.handleChange}
        notFoundContent={null}
      >
        {options}
      </Select>
    );
  }
}

export default () => <SearchInput placeholder="input search text" style={{ width: 200 }} />;