[英]Remove element from Select Antd
I use Ant-design component Select / Custom dropdown ( codesandbox ) but it does not have a function to delete an item from a special dropdown menu and if you add a button for each item Option then when you click on it the item Select closes.我使用Ant-design组件Select / Custom 下拉菜单(代码和框),但它没有从特殊下拉菜单中删除项目的功能,如果您为每个项目选项添加一个按钮,那么当您单击它时,项目Select将关闭。 Who faced such a problem?谁遇到过这样的问题?
The trick here is to use event.stopPropagation()
which will just stop event bubbling to HTML elements that are higher in the hierarchy.这里的技巧是使用event.stopPropagation()
它将停止事件冒泡到层次结构中较高的 HTML 元素。
The delete handler that stops propagation.停止传播的删除处理程序。
const deleteItem = (e, index) => {
e.stopPropagation();
e.preventDefault();
const updated = [...items];
updated.splice(index, 1);
setItems(updated);
};
The whole code with a button that deletes an item from a dropdown.带有从下拉列表中删除项目的按钮的整个代码。
import React from "react";
import "antd/dist/antd.css";
import "./index.css";
import { PlusOutlined } from "@ant-design/icons";
import { Divider, Input, Select, Space, Typography, Button } from "antd";
import { useState } from "react";
const { Option } = Select;
let index = 0;
const App = () => {
const [items, setItems] = useState(["jack", "lucy"]);
const [name, setName] = useState("");
const onNameChange = (event) => {
setName(event.target.value);
};
const addItem = (e) => {
e.preventDefault();
setItems([...items, name || `New item ${index++}`]);
setName("");
};
const deleteItem = (e, index) => {
e.stopPropagation();
e.preventDefault();
const updated = [...items];
updated.splice(index, 1);
setItems(updated);
};
return (
<Select
style={{
width: 300
}}
placeholder="custom dropdown render"
dropdownRender={(menu) => (
<>
{menu}
<Divider
style={{
margin: "8px 0"
}}
/>
<Space
align="center"
style={{
padding: "0 8px 4px"
}}
>
<Input
placeholder="Please enter item"
value={name}
onChange={onNameChange}
/>
<Typography.Link
onClick={addItem}
style={{
whiteSpace: "nowrap"
}}
>
<PlusOutlined /> Add item
</Typography.Link>
</Space>
</>
)}
>
{items.map((item, index) => (
<Option key={item}>
<div
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "center"
}}
>
<div>{item}</div>
<Button onClick={(e) => deleteItem(e, index)} danger size="small">
Delete
</Button>
</div>
</Option>
))}
</Select>
);
};
export default App;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.