React点击按钮动态添加antd Tabs标签页实现问题咨询
修复方案
核心问题点
- 初始panes配置错误,默认就加入了3个标签,不符合初始不展示的要求
- 三个添加按钮没有传递对应标签的唯一标识,add方法逻辑错误,没有判断标签是否已存在,固定新增Tab 3,导致重复添加相同标签
修改后的完整代码
import React from 'react'; import { Tabs, Button } from 'antd'; import 'antd/dist/antd.css'; const { TabPane } = Tabs; class App extends React.Component { constructor(props) { super(props); // 初始状态panes为空,符合初始不展示标签的需求 this.state = { activeKey: '', panes: [], }; } onChange = activeKey => { this.setState({ activeKey }); }; onEdit = (targetKey, action) => { this[action](targetKey); }; // 接收要添加的标签信息参数 add = (tabInfo) => { const { panes } = this.state; // 先判断标签是否已存在,用key做唯一判断 const isTabExist = panes.some(pane => pane.key === tabInfo.key); if (isTabExist) { // 已存在就直接切换到对应标签 this.setState({ activeKey: tabInfo.key }); return; } // 不存在就新增标签,同时切换到新标签 const newPanes = [...panes, tabInfo]; this.setState({ panes: newPanes, activeKey: tabInfo.key }); }; remove = targetKey => { let { activeKey } = this.state; let lastIndex; this.state.panes.forEach((pane, i) => { if (pane.key === targetKey) { lastIndex = i - 1; } }); const panes = this.state.panes.filter(pane => pane.key !== targetKey); if (panes.length && activeKey === targetKey) { activeKey = lastIndex >= 0 ? panes[lastIndex].key : panes[0].key; } else if (!panes.length) { activeKey = ''; } this.setState({ panes, activeKey }); }; render() { return ( <div className="tab-section"> <div style={{ marginBottom: 16 }}> {/* 给每个按钮绑定对应要添加的标签信息 */} <Button onClick={() => this.add({ title: 'Tab 1', content: 'Content of Tab Pane 1', key: '1' })}>ADD Tab-1</Button> <Button onClick={() => this.add({ title: 'Tab 2', content: 'Content of Tab Pane 2', key: '2' })} style={{ margin: '0 8px' }}>ADD Tab-2</Button> <Button onClick={() => this.add({ title: 'Tab 3', content: 'Content of Tab Pane 3', key: '3' })}>ADD Tab-3</Button> </div> {/* 没有标签时隐藏Tabs组件避免空展示 */} {this.state.panes.length > 0 && ( <Tabs hideAdd onChange={this.onChange} activeKey={this.state.activeKey} type="editable-card" onEdit={this.onEdit} > {this.state.panes.map(pane => ( <TabPane tab={pane.title} key={pane.key}> {pane.content} </TabPane> ))} </Tabs> )} </div> ); } } export default App;
功能说明
- 初始页面只展示三个添加按钮,无标签页
- 点击对应添加按钮,若对应标签不存在则新增,若已存在则直接切换到该标签
- 标签支持正常关闭操作,全部关闭后回到仅展示按钮的初始状态
内容的提问来源于stack exchange,提问作者Thomas Deepak Konreddy
相关产品推荐
相关产品推荐

