https://jsfiddle.net/t5q37nbe/2/
首先,我使用 AntDesign 庫創建了一個選項卡部分。我遇到的問題是 Tab-1 是默認選項卡。代碼運行后,它會自動打開 Tab-1。單擊添加 Tab-1 按鈕時,會彈出另一個 tab-1。我不希望這種情況發生。單擊 Tab-1 時,它不應再次打開新選項卡。
在這里,我將焦點和打開窗格設定為“1”,以便默認設定,
this.state = {
focusingPaneKey: '1',
openingPaneKeys: [1],
}
任何人都可以幫助我解決這個故障。
uj5u.com熱心網友回復:
反應代碼:
const { Tabs, Button } = antd
const { TabPane } = Tabs
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
focusingPaneKey: '1',
openingPaneKeys: ['1'],
}
}
openPane = (paneKey) => {
this.setState(({ ...state }) => {
if (!state.openingPaneKeys.includes(paneKey)) {
state.openingPaneKeys = [...state.openingPaneKeys, paneKey]
}
state.focusingPaneKey = paneKey
return state
})
}
closePane = (paneKey) => {
this.setState(({ ...state }) => {
if (paneKey === state.focusingPaneKey) {
const paneKeyIndex = state.openingPaneKeys.indexOf(paneKey)
state.focusingPaneKey = state.openingPaneKeys[paneKeyIndex - 1]
}
state.openingPaneKeys = state.openingPaneKeys.filter((openingPaneKey) => openingPaneKey !== paneKey)
return state
})
}
handleTabsEdit = (key, action) => {
if (action === 'remove') {
this.closePane(key)
}
}
render() {
const { panes } = this.props
const keysOfPane = Object.keys(panes)
return (
<div className="tab-section">
<div style={{ marginBottom: 16 }}>
{keysOfPane.map((key) => (
<Button key={key} onClick={() => this.openPane(key)}>
ADD Tab-{key}
</Button>
))}
</div>
<Tabs
hideAdd
onChange={this.openPane}
activeKey={this.state.focusingPaneKey}
type="editable-card"
onEdit={this.handleTabsEdit}
>
{this.state.openingPaneKeys
.map((key) => panes[key])
.map((pane) => (
<TabPane tab={pane.title} key={pane.key}>
{pane.content}
</TabPane>
))}
</Tabs>
</div>
)
}
}
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' },
}
ReactDOM.render(<App panes={panes} />, document.getElementById('container'))
問題在于 openingPaneKeys 陣列的型別。您需要在代碼中進行以下更改。
this.state = {
focusingPaneKey: '1',
openingPaneKeys: ['1'],
}
}
當您檢查!state.openingPaneKeys.includes(paneKey)時,此處的paneKey是一個字串(即“1”),但state.openingPaneKeys有[1](一個數字)。由于 1 與“1”不同,因此在您的情況下它回傳 false。
小提琴的完整作業代碼 - https://jsfiddle.net/zs8ty3fc/1/
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/440212.html
標籤:javascript 反应
上一篇:如何對右側升序的字母和左側降序的數字進行排序(來自用戶輸入的字串)?我是學習js的新手
下一篇:將物件陣列中的缺失資料設定為零
