如何使用React useState阻止计数减少至负数,停在0值?
解决React购物车计数不能低于0的问题
有两种实用方案可以实现计数减到0后不再减少的需求:
方案一:点击事件中添加判断逻辑
直接在减号按钮的点击回调里判断当前计数,只有当count > 0时才执行减1操作,避免出现负数:
<div className="border-2 rounded-lg leading-[23.8px]"> <div className="flex items-start justify-center gap-2 "> {/* 修改减号按钮的onClick逻辑 */} <button onClick={() => { if (count > 0) { setCount(count - 1); } }} className="flex self-center p-2 text-[red] hover:bg-[red] hover:text-white rounded active:bg-red-700" > <IoIosRemove /> </button> <div className="flex self-center"> <p>{count}</p> </div> <button onClick={() => setCount(count +1)} className="flex self-center p-2 text-[red] hover:bg-[red] hover:text-white rounded active:bg-red-700" > <IoIosAdd /> </button> </div> </div>
也可以简化成短路写法:onClick={() => count > 0 && setCount(count - 1)}
方案二:禁用减号按钮(推荐)
当计数为0时,直接禁用减号按钮,同时通过样式反馈给用户按钮不可点击,体验更友好:
<div className="border-2 rounded-lg leading-[23.8px]"> <div className="flex items-start justify-center gap-2 "> {/* 添加disabled属性和禁用状态样式 */} <button onClick={() => setCount(count - 1)} disabled={count === 0} className={`flex self-center p-2 text-[red] hover:bg-[red] hover:text-white rounded active:bg-red-700 ${count === 0 ? 'opacity-50 cursor-not-allowed pointer-events-none' : ''}`} > <IoIosRemove /> </button> <div className="flex self-center"> <p>{count}</p> </div> <button onClick={() => setCount(count +1)} className="flex self-center p-2 text-[red] hover:bg-[red] hover:text-white rounded active:bg-red-700" > <IoIosAdd /> </button> </div> </div>
这里的pointer-events-none用来确保禁用时按钮不响应点击,opacity-50和cursor-not-allowed让用户直观感受到按钮不可用。
内容的提问来源于stack exchange,提问作者Anas 169
相关产品推荐
相关产品推荐

