NodeJS 我怎样才能停止计数在0 [重复]

dbf7pr2w  于 2022-12-18  发布在  Node.js
关注(0)|答案(2)|浏览(95)

此问题在此处已有答案

How to stop negative number with react hooks?(3个答案)
2天前关闭。
我正在使用使用状态,希望在0处停止计数,单击时将进入-1、-2、-3等(添加到购物车按钮)

<div className="border-2 rounded-lg leading-[23.8px]">
              <div className="flex items-start justify-center gap-2 ">
                <button onClick={() => 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>

当递减量达到0时,我希望使用任何if语句或按钮禁用属性

nkcskrwz

nkcskrwz1#

尝试以下操作:

onClick={() => {
if (count > 0) setCount(count-1)
}}
b1payxdu

b1payxdu2#

可以将逻辑分离为单独的函数-第一个函数用于测试计数值,并根据按钮的name在必要时更新状态,第二个函数用于测试状态是否小于/等于零(可用于禁用按钮)。

const { useState } = React;

function Example() {

  const [ count, setCount ] = useState(0);

  // Destructure the name of the button, and
  // increment/decrement the count based on its
  // value. If the count is equal or greater than zero
  // update the state
  function handleClick(e) {
    const { name } = e.target;
    const newCount = name === 'increment'
      ? count + 1
      : count - 1;
    if (newCount >= 0) setCount(newCount);
  }

  // Return true is the state is less than
  // or equal to zero
  function isDisabled() {
    return count <= 0;
  }

  return (
    <div>
      <button
        name="decrement"
        onClick={handleClick}
        disabled={isDisabled()}
      >-
      </button>
      <span className="count">{count}</span>
      <button
        name="increment"
        onClick={handleClick}
      >+
      </button>
    </div>
  );

}

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
button { width: 25px; height: 25px;}
.count { margin: 0 0.5em; }
button:disabled { background-color: #ffcccc; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

相关问题