如何将基于Ant Design Tabs的React类组件转换为函数组件
React类组件转函数组件实现方案
你可以直接使用以下转换完成的代码,核心逻辑和原类组件完全一致:
import React, { useState } from "react"; import { Tabs, Button } from 'antd'; import 'antd/dist/antd.css'; const { TabPane } = Tabs; const Tabbar = (props) => { // 替换原类组件的state为useState管理 const [focusingPaneKey, setFocusingPaneKey] = useState(''); const [openingPaneKeys, setOpeningPaneKeys] = useState([]); const openPane = (paneKey) => { setOpeningPaneKeys(prevKeys => { if (!prevKeys.includes(paneKey)) { return [...prevKeys, paneKey]; } return prevKeys; }); setFocusingPaneKey(paneKey); }; const closePane = (paneKey) => { setOpeningPaneKeys(prevKeys => { const newKeys = prevKeys.filter(openingPaneKey => openingPaneKey !== paneKey); // 处理关闭当前激活标签的逻辑 if (paneKey === focusingPaneKey) { const paneKeyIndex = prevKeys.indexOf(paneKey); setFocusingPaneKey(newKeys[paneKeyIndex - 1] || ''); } return newKeys; }); }; const handleTabsEdit = (key, action) => { if (action === 'remove') { closePane(key); } }; const { panes } = props; const keysOfPane = Object.keys(panes); return ( <div className="tab-section"> <div style={{ marginBottom: 16 }}> {keysOfPane.map((key) => ( <Button key={key} onClick={() => openPane(key)}> ADD Tab-{key} </Button> ))} </div> <Tabs hideAdd onChange={openPane} activeKey={focusingPaneKey} type="editable-card" onEdit={handleTabsEdit} > {openingPaneKeys .map((key) => panes[key]) .map((pane) => ( <TabPane tab={pane.title} key={pane.key}> {pane.content} </TabPane> ))} </Tabs> </div> ); }; // 示例panes配置你可以根据需求放到父组件传入,这里保留原代码定义 export const panes = { 1: { key: '1', title: 'Tab 1', content: 'Content of Tab Pane 1' }, 2: { key: '2', title: 'Tab 2', content: 'Content of Tab Pane 2' }, 3: { key: '3', title: 'Tab 3', content: 'Content of Tab Pane 3' }, }; export default Tabbar;
核心改动点
- 移除
class定义和constructor构造函数,改用函数声明定义组件 - 原类组件的合并状态拆分为两个独立的
useState状态变量管理,避免冗余的状态合并操作 - 所有方法去掉
this绑定,直接作为函数内部的普通方法调用 - 原
setState的回调参数改为useState自带的更新函数,用prev开头的变量读取上一次的状态值,保证状态更新的准确性
内容的提问来源于stack exchange,提问作者Thomas Deepak Konreddy
相关产品推荐
相关产品推荐

