【问题标题】:When I click on the button, if the value of the button is 0, then the text will not show in that space. I mean, how can it be done without showing 10?当我单击按钮时,如果按钮的值为 0,则文本不会显示在该空间中。我的意思是,不显示 10 怎么办?
【发布时间】:2022-09-29 13:11:19
【问题描述】:

当我单击按钮时,如果按钮的值为 0,则文本不会显示在该空间中。我的意思是,不显示-10怎么办?

console.log(variable)

这是我得到的错误..


const Mobile = () => {

   const [charge, setCharge] = useState(20)

   const setMobileCharge = () => setCharge(charge - 10)

   if (setMobileCharge === 0) {
      return 0;
   }

   return (
      <div>
         <h3>Charge : {charge}</h3>
         <button onClick={setMobileCharge}>Battery down</button>
      </div>
   );
};

导出默认手机;

    标签: javascript reactjs react-component


    【解决方案1】:

    发生这种情况是因为反应“滴答”你的渲染没有与状态完全同步......所以为了防止你可以像这样设置新状态

    setCharge(oldCharge => oldCharge -10 )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-29
      • 2020-11-13
      • 1970-01-01
      相关资源
      最近更新 更多