如何为Ant Design AutoComplete选项添加删除图标实现删除功能
实现AutoComplete选项添加删除图标并支持删除功能
你可以通过以下步骤修改代码,实现每个选项旁添加删除图标并点击删除的功能:
关键修改点
- 将
options改为受控状态,用useState管理,这样删除后能实时更新选项列表 - 使用AutoComplete的
renderOption属性自定义选项渲染,加入删除图标 - 实现删除函数,点击图标时过滤掉对应选项
完整代码示例
import { useState } from 'react'; import { AutoComplete, Input, Button } from 'antd'; import { SearchOutlined, DeleteOutlined } from '@ant-design/icons'; // 假设你的styles和其他函数已定义 const YourComponent = () => { const [searchText, setSearchText] = useState(''); // 将options改为受控状态 const [options, setOptions] = useState([ { value: 'Burns Bay Road' }, { value: 'Downing Street' }, { value: 'Wall Street' } ]); const handleChangedSearchText = (e) => { setSearchText(e.target.value); }; const handleSubmit = (e) => { e.preventDefault(); // 这里写你的提交逻辑 }; // 处理选项删除 const handleDeleteOption = (value) => { setOptions(prevOptions => prevOptions.filter(opt => opt.value !== value)); }; return ( <form onSubmit={handleSubmit}> <AutoComplete options={options} filterOption={(inputValue, option) => option!.value.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1 } // 自定义选项渲染,添加删除图标 renderOption={(option) => ( <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '4px 8px' }}> <span>{option.value}</span> <DeleteOutlined onClick={() => handleDeleteOption(option.value)} style={{ cursor: 'pointer', color: '#ff4d4f' }} /> </div> )} > <Input value={searchText} maxLength={50} onKeyPress={(event) => { if (/[0-9]/.test(event.key)) { event.preventDefault(); } }} className={styles.input} style={{ width: 364, height: 44, padding: 12 }} placeholder='Search..' onChange={handleChangedSearchText} /> </AutoComplete> <Button htmlType='submit' className={styles.button_search} style={{ width: 44, height: 44 }} icon={<SearchOutlined className={styles.icon_search} />} /> </form> ); }; export default YourComponent;
代码说明
- 受控状态管理:用
useState初始化选项列表,删除时通过setOptions更新状态,确保UI同步刷新 - 自定义选项布局:
renderOption返回flex布局的元素,让选项文本左对齐、删除图标右对齐,点击图标触发删除逻辑 - 删除逻辑实现:
handleDeleteOption通过filter方法移除目标选项,生成新的选项数组更新状态
内容的提问来源于stack exchange,提问作者Little
相关产品推荐
相关产品推荐

