antd tab组件怎么使用hooks?

antd tab组件怎么使用hooks?
https://ant.design/components...

官网的add和remove也没有调用,,没看懂onEdit怎么用,没有this怎么操作?

回答

我用函数组件重写了一下,那个 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"));

以上是 antd tab组件怎么使用hooks? 的全部内容, 来源链接: utcz.com/a/99133.html

回到顶部