ant-design/components/select/demo/search-box.md

96 lines
2.0 KiB
Markdown
Raw Normal View History

2016-03-31 09:40:55 +08:00
---
order: 9
2016-10-06 18:54:28 +08:00
title:
2016-07-10 08:55:43 +08:00
zh-CN: 搜索框
en-US: Search Box
2016-03-31 09:40:55 +08:00
---
2016-07-10 08:55:43 +08:00
## zh-CN
2018-06-19 14:37:35 +08:00
搜索和远程数据结合。
2016-07-10 08:55:43 +08:00
## en-US
2018-06-19 14:37:35 +08:00
Search with remote data.
2016-07-10 08:55:43 +08:00
```tsx
2017-01-05 15:47:19 +08:00
import { Select } from 'antd';
2016-12-19 17:54:25 +08:00
import jsonp from 'fetch-jsonp';
import qs from 'qs';
2022-05-21 22:14:15 +08:00
import React, { useState } from 'react';
2018-06-27 15:55:04 +08:00
const { Option } = Select;
let timeout: ReturnType<typeof setTimeout> | null;
let currentValue: string;
const fetch = (value: string, callback: (data: { value: string; text: string }[]) => void) => {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
currentValue = value;
const fake = () => {
const str = qs.stringify({
code: 'utf-8',
q: value,
});
2016-12-19 17:54:25 +08:00
jsonp(`https://suggest.taobao.com/sug?${str}`)
.then((response: any) => response.json())
.then((d: any) => {
2016-12-19 17:54:25 +08:00
if (currentValue === value) {
2019-06-19 19:09:08 +08:00
const { result } = d;
const data = result.map((item: any) => ({
value: item[0],
text: item[0],
}));
2016-12-19 17:54:25 +08:00
callback(data);
}
});
};
timeout = setTimeout(fake, 300);
};
const SearchInput: React.FC<{ placeholder: string; style: React.CSSProperties }> = props => {
const [data, setData] = useState<any[]>([]);
const [value, setValue] = useState<string>();
2018-06-27 15:55:04 +08:00
const handleSearch = (newValue: string) => {
if (newValue) {
fetch(newValue, setData);
} else {
setData([]);
}
2019-05-07 14:57:32 +08:00
};
const handleChange = (newValue: string) => {
setValue(newValue);
2019-05-07 14:57:32 +08:00
};
2018-06-27 15:55:04 +08:00
const options = data.map(d => <Option key={d.value}>{d.text}</Option>);
return (
<Select
showSearch
value={value}
placeholder={props.placeholder}
style={props.style}
defaultActiveFirstOption={false}
showArrow={false}
filterOption={false}
onSearch={handleSearch}
onChange={handleChange}
notFoundContent={null}
>
{options}
</Select>
);
};
const App: React.FC = () => <SearchInput placeholder="input search text" style={{ width: 200 }} />;
export default App;
2019-05-07 14:57:32 +08:00
```