Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

antd tab组件怎么使用hooks?

image.png
https://ant.design/components...

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...