需求
用antd实现类似百度搜索框,带搜索的input文本输入框
分析
antd <Select> 有自带搜索的功能,但搜索后必须选择已有筛选项,不能自定义输入
antd <Input> 没有发现有类似带搜索的功能(maybe没发现,如果有同学发现,请联系我,感谢)
可以使用: antd <AutoComplete>
实现
官方实现: <AutoComplete> filterOption
使用
<AutoComplete>
的filterOption
antd <AutoComplete> 有自动带出option功能:
官方代码:
import { AutoComplete } from 'antd';
const options = [
{ value: 'Burns Bay Road' },
{ value: 'Downing Street' },
{ value: 'Wall Street' },
];
const Complete: React.FC = () => (
<AutoComplete
style={{ 200 }}
options={options}
placeholder="try to type `b`"
filterOption={(inputValue, option) =>
option!.value.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
}
/>
);
ReactDOM.render(<Complete />, mountNode);
基于 <AutoComplete> onSearch 改写
对 <AutoComplete> 的
onSearch
事件进行了改写,根据输入值更新options
import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { AutoComplete } from 'antd';
const { Option } = AutoComplete;
const Complete = () => {
const [result, setResult] = useState([]);
const [sourceList, setSourceList] = useState([]);
useEffect(() => {
setSourceList(['a', 'aa', 'aaa', 'aaaa']);
}, []);
const handleSearch = value => {
let res = [];
value && sourceList.forEach(item => item.includes(value) && res.push(item));
setResult(res);
};
return (
<AutoComplete
style={{ 200}}
onSearch={handleSearch}
placeholder="input with select"
>
{result.map(item => (
<Option key={item} value={item}>
{item}
</Option>
))}
</AutoComplete>
);
};
ReactDOM.render(<Complete />, document.getElementById('container'));
代码地址:antd input with select
演示地址:(https://antd-input-with-select.stackblitz.io)