我有這個setState來控制我的面板打開/關閉狀態。而且我想open one panel at one time這樣只會有一個在真正的價值state。
這是我的代碼:
// Parents component
const [show, setShow] = useState({
1 : false, // id=1 when passed to child component (using another props but
2 : false, // dont worry, I'm passing it correctly)
3 : false, // id=3 and so on...
4 : false,
5 : false,
6 : false
})
//Child component
// id is used to check which panel is in open/close state
const handleShowPanel = (id) => {
const val = !props.show
// props.setShow(prev => ({...prev, [key[0].charCodeAt(0)]: false}))
props.setShow(prev => ({...prev, [id] : val})) //this is the one i'm using
// props.setShow(prev => Object.fromEntries(Object.entries(prev).map(([k, v]) => Number(k) !== id ? [k, !v] : [k, false])))
}
我使用的代碼可以很好地打開和關閉一個面板。
這里有一個更好的說明圖片,讓我們先說我開了Panel 1,在那之后,當我點擊Panel 2我要關閉面板1時opening Panel 2。因此,除了我打開的面板之外,我必須將所有其他值設定為 false 。就像螞蟻設計中的手風琴模式
uj5u.com熱心網友回復:
如果您只想一次打開一個面板,那么為什么不只存盤您想要打開的面板的 ID?
const [showId, setShowId] = useState(null); // <-- initially none open
const handleShowPanel = (id) => {
// if already open, close it, otherwise set to new id to
// close previous and open next
setShowId(showId => showId === id ? null : id);
};
然后在映射/渲染面板時,只需id根據當前設定的showId狀態值檢查當前面板的值,以相應地設定打開狀態/道具。
uj5u.com熱心網友回復:
在這種情況下,您可能不需要保持所有面板的顯示狀態,只需保持打開的面板索引試試這種方式
const panels = [
{id:1, name:'name1', description:'description 11'},
{id:1, name:'name2', description:'description 22'},
{id:1, name:'name3', description:'description 33'},
{id:1, name:'name4', description:'description 44'},
{id:1, name:'name5', description:'description 55'},
{id:1, name:'name6', description:'description 66'}
]
const PanelParent = () => {
const [openId, setOpenId] = useState('') //set an id if you need to open a default panel
const handleShowPanel = (id) => {
setOpenIndex(openId == id ? false : id)
}
return <>
{panels.map(d => {
return <Panel data={d} handleShowPanel={handleShowPanel} open={openId == d.id}/>
})}
</>
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/358393.html
標籤:javascript 反应 反应钩子 蚂蚁
上一篇:基于比較運算子的顯示元素
