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(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(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 (
    
{panes.map((pane) => ( {pane.content} ))}
); }; ReactDOM.render(, document.getElementById("container"));