亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何減少模態使用 useState 的次數?

如何減少模態使用 useState 的次數?

慕沐林林 2023-03-24 13:56:47
我有一個關于在一個 useState 中使用多個狀態的問題。我有兩個按鈕(大約 10 個),單擊按鈕后,它會顯示一些典型信息,僅適用于一個按鈕(選擇)。所以每個按鈕的狀態必須是單獨的。有什么方法可以將所有按鈕減少到一個 useState 嗎?我現在有:  const [showConfirmModalGoals, setShowConfirmModalGoals] = useState(false);  const [showConfirmModalBallPos, setShowConfirmModalBallPos] = useState(false);    const showModalForGoals = () => {    setShowConfirmModalGoals(true);  };    const hideModalForGoals = () => {    setShowConfirmModalGoals(false);  };  const showModalForBallPos = () => {    setShowConfirmModalBallPos(true);  };    const hideModalForBallPos = () => {    setShowConfirmModalBallPos(false);  };return(<Modal show={showConfirmModalGoals} ... > GOALS </Modal><Button onClick={showModalForGoals} /><Modal show={showConfirmModalBallPos} ... > Ball position</Modal><Button onClick={showModalForBallPos} />);所以如果我要 10 個不同內容的按鈕,我需要這些按鈕有 10 個不同的狀態。
查看完整描述

2 回答

?
四季花海

TA貢獻1811條經驗 獲得超5個贊

不!所有按鈕只需要一個模式。

const [showModal, setShowModal] = useState(false);

然后,對于每個按鈕:

<Button onClick={() => setShowModal(true)} />

然后您將根據單擊的按鈕更改模態框的內容(頁眉、正文和頁腳)。


查看完整回答
反對 回復 2023-03-24
?
慕無忌1623718

TA貢獻1744條經驗 獲得超4個贊

您可以為所有狀態使用一個對象。


const [showConfirmModals, setShowConfirmModals] = useState({

  showConfirmModalGoals: false,

  showConfirmModalBallPos: false,

});


// ...


setShowConfirmModals({

  ...showConfirmModals,

  showConfirmModalGoals: true

})


查看完整回答
反對 回復 2023-03-24
  • 2 回答
  • 0 關注
  • 126 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號