我用函数组件重写了一下,那个 action 其实就是调了下 remove
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Tabs, Button } from "antd";
const { TabPane } = Tabs;
const Demo: React.FC = () => {
const [newTabIndex, setNewTabIndex] = useState<number>(0);
const [panes, setPanes] = useState([
{ title: "Tab 1", content: "Content of Tab Pane 1", key: "1" },
{ title: "Tab 2", content: "Content of Tab Pane 2", key: "2" }
]);
const [activeKey, setActiveKey] = useState<string>(panes[0]?.key);
const onChange = (activeKey: string) => {
setActiveKey(activeKey);
};
const add = () => {
const activeKey = `newTab${newTabIndex + 1}`;
setNewTabIndex(newTabIndex + 1);
panes.push({ title: "New Tab", content: "New Tab Pane", key: activeKey });
setActiveKey(activeKey);
setPanes(panes);
};
const remove = (targetKey) => {
let lastIndex;
panes.forEach((pane, i) => {
if (pane.key === targetKey) {
lastIndex = i - 1;
}
});
const tempPanes = panes.filter((pane) => pane.key !== targetKey);
if (tempPanes.length && activeKey === targetKey) {
if (lastIndex >= 0) {
setActiveKey(tempPanes[lastIndex].key);
} else {
setActiveKey(tempPanes[0].key);
}
}
setActiveKey(activeKey);
setPanes(tempPanes);
};
const onEdit = (targetKey, action) => {
remove(targetKey);
};
return (
<div>
<div style={{ marginBottom: 16 }}>
<Button onClick={add}>ADD</Button>
</div>
<Tabs
hideAdd
onChange={onChange}
activeKey={activeKey}
type="editable-card"
onEdit={onEdit}
>
{panes.map((pane) => (
<TabPane tab={pane.title} key={pane.key}>
{pane.content}
</TabPane>
))}
</Tabs>
</div>
);
};
ReactDOM.render(<Demo />, document.getElementById("container"));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…