ant-design/components/select/demo/search-box.md
黑雨 91821d4d3a
feat: select edit demo to data driven (#37601)
* feat: select edit demo to data driven

* feat: edit demo to data driven

Co-authored-by: 二货机器人 <smith3816@gmail.com>
2022-09-19 18:01:16 +08:00

95 lines
2.0 KiB
Markdown

---
order: 9
title:
zh-CN: 搜索框
en-US: Search Box
---
## zh-CN
搜索和远程数据结合。
## en-US
Search with remote data.
```tsx
import React, { useState } from 'react';
import { Select } from 'antd';
import jsonp from 'fetch-jsonp';
import qs from 'qs';
import type { SelectProps } from 'antd';
let timeout: ReturnType<typeof setTimeout> | null;
let currentValue: string;
const fetch = (value: string, callback: Function) => {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
currentValue = value;
const fake = () => {
const str = qs.stringify({
code: 'utf-8',
q: value,
});
jsonp(`https://suggest.taobao.com/sug?${str}`)
.then((response: any) => response.json())
.then((d: any) => {
if (currentValue === value) {
const { result } = d;
const data = result.map((item: any) => ({
value: item[0],
text: item[0],
}));
callback(data);
}
});
};
timeout = setTimeout(fake, 300);
};
const SearchInput: React.FC<{ placeholder: string; style: React.CSSProperties }> = props => {
const [data, setData] = useState<SelectProps['options']>([]);
const [value, setValue] = useState<string>();
const handleSearch = (newValue: string) => {
if (newValue) {
fetch(newValue, setData);
} else {
setData([]);
}
};
const handleChange = (newValue: string) => {
setValue(newValue);
};
return (
<Select
showSearch
value={value}
placeholder={props.placeholder}
style={props.style}
defaultActiveFirstOption={false}
showArrow={false}
filterOption={false}
onSearch={handleSearch}
onChange={handleChange}
notFoundContent={null}
options={(data || []).map(d => ({
value: d.value,
label: d.text,
}))}
/>
);
};
const App: React.FC = () => <SearchInput placeholder="input search text" style={{ width: 200 }} />;
export default App;
```