import React, { useState } from 'react';
import { Tag } from 'antd';
const MyComponent = () => {
const [tags, setTags] = useState(['Tag 1', 'Tag 2']);
const handleDelete = (removedTag) => {
const newTags = tags.filter((tag) => tag !== removedTag);
setTags(newTags);
};
return (
{tags.map((tag) => (
handleDelete(tag)}>
{tag}
))}
);
};
export default MyComponent;
在此示例中,我们为每个标签设置了key属性,以确保当标签被删除时,组件会重新渲染。
import React, { useState } from 'react';
import { Tag } from 'antd';
const MyComponent = () => {
const [tags, setTags] = useState(['Tag 1', 'Tag 2']);
const [forceUpdate, setForceUpdate] = useState(false);
const handleDelete = (removedTag) => {
const newTags = tags.filter((tag) => tag !== removedTag);
setTags(newTags);
setForceUpdate(!forceUpdate);
};
return (
{tags.map((tag) => (
handleDelete(tag)}>
{tag}
))}
);
};
export default MyComponent;
在此示例中,我们在标签被删除时强制组件重新渲染,以确保标签列表始终更新。