React无状态组件+Antd(Tabs)删除添加功能
import {
Tabs } from antd;
const {
TabPane } = Tabs;
const initialPanes = [
{
title: Tab 1, content: Content of Tab 1, key: 1 },
{
title: Tab 2, content: Content of Tab 2, key: 2 },
{
title: Tab 3, content: Content of Tab 3, key: 3, },
];
class Demo extends React.Component {
newTabIndex = 0;
state = {
activeKey: initialPanes[0].key,
panes: initialPanes,
};
onChange = activeKey => {
this.setState({
activeKey });
};
onEdit = (targetKey, action) => {
this[action](targetKey);
};
add = () => {
const {
panes } = this.state;
const activeKey = `newTab${
this.newTabIndex++}`;
const newPanes = [...panes];
newPanes.push({
title: New Tab, content: Content of new Tab, key: activeKey });
this.setState({
panes: newPanes,
activeKey,
});
};
remove = targetKey => {
const {
panes, activeKey } = this.state;
let newActiveKey = activeKey;
let lastIndex;
panes.forEach((pane, i) => {
if (pane.key === targetKey) {
lastIndex = i - 1;
}
});
const newPanes = panes.filter(pane => pane.key !== targetKey);
if (newPanes.length && newActiveKey === targetKey) {
if (lastIndex >= 0) {
newActiveKey = newPanes[lastIndex].key;
} else {
newActiveKey = newPanes[0].key;
}
}
this.setState({
panes: newPanes,
activeKey: newActiveKey,
});
};
render() {
const {
panes, activeKey } = this.state;
return (
<Tabs
type="editable-card"
onChange={
this.onChange}
activeKey={
activeKey}
onEdit={
this.onEdit}
>
{
panes.map(pane => (
<TabPane tab={
pane.title} key={
pane.key} closable={
pane.closable}>
{
pane.content}
</TabPane>
))}
</Tabs>
);
}
}
ReactDOM.render(<Demo />, mountNode);
先看Antd源码,因为class组件中有this,生命周期,他在onEditthis[action](targetKey)进行了一系列🐂b操作。
那么在函数组件+hook开发没有this,当你按他写发来的话
const onEdit = (targetKey, action) => {
// 这个时候this是undefined所以也是取不到的。
this[action](targetKey);
//或者把this删了?还不行
};
解决办法
如果你看了他的API的话可以看到onEdit有两个参数targetKey,action,这里targetKey对应initialPanes里的key,action就是你触发的类型,打印的话可以看到’add’, ‘delete’;那么只需要判断一下就OK啦!是不是特别简单?
const onEdit = (targetKey: any, action: any) => {
console.log(action:, action)
if (action === remove) {
remove(targetKey) // remove方法
}
if (action === add) {
add(targetKey) // add方法
}
}
<Tabs
activeKey={
tabIndex}
type="editable-card"
tabBarGutter={
4}
onEdit={
(targetKey, action) => onEdit(targetKey, action)} >
{
panes &&
panes.map((pane: any) => (
<TabPane tab={
pane.title} key={
pane.key}>
{
pane.content}
</TabPane>
))}
</Tabs>
