javascript
import { useState } from 'react';
import { Select, Spin } from 'antd';
const { Option } = Select;
const RemoteSearchSelect = () => {
const [loading, setLoading] = useState(false);
const [options, setOptions] = useState([]);
const fetchData = async (value) => {
setLoading(true);
// 模拟调用接口获取数据
try {
const response = await fetch(`https://api.example.com/search?q=${value}`);
const data = await response.json();
if (data.length > 0) {
setOptions(data);
} else {
setOptions([]);
}
} catch (error) {
console.error('Error fetching data:', error);
}
setLoading(false);
};
const handleSearch = (value) => {
// 远程搜索数据
fetchData(value);
};
return (
<Select
showSearch
onSearch={handleSearch}
placeholder="搜索"
notFoundContent={loading ? <Spin size="small" /> : options.length === 0 ? "暂无数据" : null}
>
{options.map((option) => (
<Option key={option.value} value={option.value}>
{option.label}
</Option>
))}
</Select>
);
};
export default RemoteSearchSelect;