我有一個應該減少數字的按鈕。當我的數字在 React 中為 1 時,如何創建一個停止減少的條件?
<Button type="button" size="small" onClick={() =>
handleUpdateCartQty(item.id, item.quantity - 1)}>-</Button>
類似的東西:
if(item.quantity == 1){
<Button type="button" size="small" onClick={() =>
handleUpdateCartQty(item.id, item.quantity)}>-</Button>
}else{
<Button type="button" size="small" onClick={() =>
handleUpdateCartQty(item.id, item.quantity - 1)}>-</Button>
}
筆記
item.quantity 保存數字的值
uj5u.com熱心網友回復:
我會為此目的使用Math.max
<Button type="button" size="small" onClick={() =>
handleUpdateCartQty(item.id, Math.max(0, item.quantity - 1)}>-</Button>
uj5u.com熱心網友回復:
只需您可以使用三元運算子作為handleUpdateCartQty引數,例如:
<Button type="button" size="small" onClick={() =>
handleUpdateCartQty(item.id, item.quantity <= 1 ? item.quantity : item.quantity - 1)}>-</Button>
uj5u.com熱心網友回復:
我必須指出,使用onclick. 我建議您嘗試addEventListener改用。
在這里查看更多
document.querySelector('button').addEventListener('click', function() {
if (item.quantity > 1) {
handleUpdateCartQty(item.id, item.quantity)
item.quantity--;
}
})
<button type="button" size="small" >-</Button>
uj5u.com熱心網友回復:
可能有多種方法可以實作這一目標
讓我與您分享2種方法,以便您可以根據需要選擇一種
如果一個按鈕減少計數,那么可能有另一種方法來增加計數
如果是這種情況,那么您可以在您的值為 1 時立即禁用遞減計數按鈕
disabled={newValue<=1}
另一種方法是if在函式中添加條件
const handleUpdateCartQty = (id, newVal) => {
if(newVal < 1) {
// showNotification('min allowed quantity is 1');
return;
}
// Do update operation
}
如果您沒有禁用按鈕并且沒有顯示任何通知,即min quantity should be 1在您的代碼中處理條件時,它可能會給用戶留下按鈕不起作用的印象
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/406773.html
標籤:
