問題描述
React‑Bootstrap 選項卡 defaultActiveKey 不隨 stateChange 改變 (React‑Bootstrap Tabs defaultActiveKey is not changing with stateChange)
不會隨著 State 的變化而改變 defaultActiveKey。
- 我有默認情況下打開“寫入” 一個案例場景的選項卡
- 然後默認打開“閱讀”;另一個案例場景的選項卡
我的代碼是這樣的
this.state = {
defaultTab: "write"
}
functionToChangeDefaultTab()=>{
this.setState({defaultTab: "read"})
}
render(){
return(
<Tabs defaultactivekey={this.state.defaultTab} transition={false} onSelect={this.onTabSelected}>
<Tab eventKey="read" title="read"></Tab>
<Tab eventKey="write" title="write"></Tab>
.
.
</Tabs>
);
}
即使在運行 setState defaultTab 的函數後“讀取” 值,“寫”;選項卡打開。我不知道,如何動態放置defaultActiveTab。
參考解法
方法 1:
it seems your issues come from
- wrong props ❌defaultactivekey passed to Tabs component
‑‑> should be camelCase: ✅defaultActiveKey - your function syntaxe depends on class based component. if it is the case, I reckon you wanted to do the following
</ul>
class NAMEOFYOURCOMPONENT extends React.Component {
/* ‑ This syntax ensures `this` is bound within functionToChangeDefaultTab.
‑ Warning: this is *experimental* syntax.
( from react's doc see: https://reactjs.org/docs/handling‑events.html)
‑ you wrote: ❌ functionToChangeDefaultTab()=>{ ... } */
// ✅ should be
functionToChangeDefaultTab = () => {
// ... code ...
}
render() {
return (
{/* ... code ... */}
);
}
}
Then it should work.
方法 2:
why you are not using activeKey prop and passing your state
<Tabs
activeKey={activeTab}
id="uncontrolled‑tab‑example"
onSelect={(k) => {
setactiveTab(k || '');
nevagitation({
search: `?tab=${k}`,
});
}}
className="bluebordertabs"
>
//other code
</Tabs>
(by Pankti Bardolia、Laureline、usman)