【问题标题】:Button within a tab to switch tabs using Ant Design in React?在 React 中使用 Ant Design 切换选项卡的选项卡中的按钮?
【发布时间】:2021-08-11 22:09:32
【问题描述】:
希望在标签正文中放置一个按钮,该按钮只会切换到下一个标签,反之亦然。我已经玩了几个小时了,但找不到解决方法。任何帮助表示赞赏
import { Tabs } from 'antd';
const { TabPane } = Tabs;
function callback(key) {
console.log(key);
}
const Demo = () => (
<Tabs defaultActiveKey="1" onChange={callback}>
<TabPane tab="Tab 1" key="1">
Content of Tab Pane 1
<button type="button">
Go to tab 2
</button>
</TabPane>
<TabPane tab="Tab 2" key="2">
Content of Tab Pane 2
</TabPane>
<TabPane tab="Tab 3" key="3">
Content of Tab Pane 3
</TabPane>
</Tabs>
);
ReactDOM.render(<Demo />, mountNode);
【问题讨论】:
标签:
javascript
reactjs
jsx
antd
【解决方案1】:
您需要使用activeKey属性并将activeKey保存在状态中。
import React from 'react'
import { Tabs } from 'antd';
const { TabPane } = Tabs;
function Demo () {
const [activeKey, setActiveKey] = React.useState('1')
const onKeyChange = (key) => setActiveKey(key)
return (
<Tabs defaultActiveKey="1" activeKey={activeKey} onChange={onKeyChange}>
<TabPane tab="Tab 1" key="1">
Content of Tab Pane 1
<button onClick={() => onKeyChange('2')}>Go to "Tab 2"</button>
</TabPane>
<TabPane tab="Tab 2" key="2">
Content of Tab Pane 2
<button onClick={() => onKeyChange('1')}>Go to "Tab 1"</button>
</TabPane>
<TabPane tab="Tab 3" key="3">
Content of Tab Pane 3
</TabPane>
</Tabs>
)
}
ReactDOM.render(<Demo />, document.getElementById('root'));
我没有测试过自己,但它应该能让你知道如何去做。