ant-design/components/select/demo/search-box.tsx
afc163 59ad48476b
refactor: add boime lint and fix lint errrors ()
* chore: add boime lint

* fix lint

* use files ignore

* revert change

* ignore clarity.js

* fix some errors

* fix some errors

* fix some errors

* fix some errors

* add yml file

* Update clarity.js

Signed-off-by: afc163 <afc163@gmail.com>

* add npm run lint:biome

* add npm run lint:biome

* fix test case

* fix ts errors

* fix ts errors

* fix lint and add .lintstagedrc

* shorten prop name

* chore: update package.json

* update biome.json

* chore: remove stylelint

* chore: useOptionalChain

* fix lint

* biome format

* prettier all code

* prettier all code

* fix site test

---------

Signed-off-by: afc163 <afc163@gmail.com>
2024-06-22 21:59:12 +08:00

77 lines
1.9 KiB
TypeScript

import React, { useState } from 'react';
import { Select } from 'antd';
import type { SelectProps } from 'antd';
import jsonp from 'fetch-jsonp';
import qs from 'qs';
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);
}
});
};
if (value) {
timeout = setTimeout(fake, 300);
} else {
callback([]);
}
};
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) => {
fetch(newValue, setData);
};
const handleChange = (newValue: string) => {
setValue(newValue);
};
return (
<Select
showSearch
value={value}
placeholder={props.placeholder}
style={props.style}
defaultActiveFirstOption={false}
suffixIcon={null}
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;