在我的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>
};
答案 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>
);
};