ant-design/components/tabs/demo/custom-add-trigger.md
章鱼 7fd093bd0a
docs: feat components TS demo (#34742)
* docs: add general components TS demo

* docs: add layout components TS demo

* docs: add navigation components TS demo

* docs: add data entry components TS demo

* chore(deps): add types for qs

* docs: add data display TS demo

* docs: add feedback components TS demo

* docs: add other components TS demo

* chore(deps): add types

* docs: unified demo code style

* docs: fix lint error

* docs: add demo TS type

* docs: fix demo TS type

* test: update snapshot

* docs: fix TS demo

* feat: update Rate character type

* docs: fix lint error

* feat: update Rate character type

* feat: update Rate character type
2022-05-19 09:46:26 +08:00

88 lines
2.1 KiB
Markdown

---
order: 11
title:
zh-CN: 自定义新增页签触发器
en-US: Customized trigger of new tab
---
## zh-CN
隐藏默认的页签增加图标,给自定义触发器绑定事件。
## en-US
Hide default plus icon, and bind event for customized trigger.
```tsx
import React, { useRef, useState } from 'react';
import { Tabs, Button } from 'antd';
const { TabPane } = Tabs;
const defaultPanes = Array.from({ length: 2 }).map((_, index) => {
const id = String(index + 1);
return { title: `Tab ${id}`, content: `Content of Tab Pane ${index + 1}`, key: id };
});
const App: React.FC = () => {
const [activeKey, setActiveKey] = useState(defaultPanes[0].key);
const [panes, setPanes] = useState(defaultPanes);
const newTabIndex = useRef(0);
const onChange = (key: string) => {
setActiveKey(key);
};
const add = () => {
const newActiveKey = `newTab${newTabIndex.current++}`;
setPanes([...panes, { title: 'New Tab', content: 'New Tab Pane', key: newActiveKey }]);
setActiveKey(newActiveKey);
};
const remove = (targetKey: string) => {
let lastIndex = -1;
panes.forEach((pane, i) => {
if (pane.key === targetKey) {
lastIndex = i - 1;
}
});
if (panes.length && activeKey === targetKey) {
let newActiveKey: string;
if (lastIndex >= 0) {
newActiveKey = panes[lastIndex].key;
} else {
newActiveKey = panes[0].key;
}
setActiveKey(newActiveKey);
}
const newPanes = panes.filter(pane => pane.key !== targetKey);
setPanes(newPanes);
};
const onEdit = (targetKey: string, action: 'add' | 'remove') => {
if (action === 'add') {
add();
} else {
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>
);
};
export default App;
```