使用react hooks不小于0

时间:2019-10-06 10:44:11

标签: reactjs react-hooks

在我的removeCountHandler中,我需要确定数字是否小于零。如果是,则将其保持为零

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

  const addCountHandler = () => {
    setCount(count + 1);
  };
  const removeCountHandler = () => {
    setCount(count - 1);
  };

  return count <= 1  ? 
    <div>
        {count} person
      <Increment increment={addCountHandler} />
      <Decrement decrement={removeCountHandler} />
    </div>
  :
   <div>
        {count} persons
      <Increment increment={addCountHandler} />
      <Decrement decrement={removeCountHandler} />
    </div>
};


1 个答案:

答案 0 :(得分:0)

查看演示: Demo

基本上,您只需在removeCountHandler中检查计数器是否为零:

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

  const addCountHandler = () => {
    setCount(count + 1);
  };
  const removeCountHandler = () => {
    if(count === 0){
      return;  
    }
    setCount(count - 1);
  };

  return (
    <div>
        {count} person
      <button onClick={addCountHandler}>+</button>
      <button onClick={removeCountHandler}>-</button>
    </div>
  );
};