mirror of
https://github.com/ant-design/ant-design.git
synced 2024-12-05 09:49:57 +08:00
7fd093bd0a
* docs: add general components TS demo * docs: add layout components TS demo * docs: add navigation components TS demo * docs: add data entry components TS demo * chore(deps): add types for qs * docs: add data display TS demo * docs: add feedback components TS demo * docs: add other components TS demo * chore(deps): add types * docs: unified demo code style * docs: fix lint error * docs: add demo TS type * docs: fix demo TS type * test: update snapshot * docs: fix TS demo * feat: update Rate character type * docs: fix lint error * feat: update Rate character type * feat: update Rate character type
2.0 KiB
2.0 KiB
order | title | ||||
---|---|---|---|---|---|
9 |
|
zh-CN
搜索和远程数据结合。
en-US
Search with remote data.
import React, { useState } from 'react';
import { Select } from 'antd';
import jsonp from 'fetch-jsonp';
import qs from 'qs';
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,
});
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<any[]>([]);
const [value, setValue] = useState<string>();
const handleSearch = (newValue: string) => {
if (newValue) {
fetch(newValue, setData);
} else {
setData([]);
}
};
const handleChange = (newValue: string) => {
setValue(newValue);
};
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;