You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击回车键清空输入框值后,if与else分支同时触发的问题

问题原因

你遇到的两个分支同时触发的问题,根源是重复绑定了keyup事件监听器:

  • useEffect的依赖数组包含amount,每次调用addAmount()更新amount时,useEffect都会重新执行,给输入框添加新的keyup事件监听器。
  • 当按下回车时,所有已绑定的监听器都会依次执行:第一个监听器拿到输入框的原始值走if分支,执行后清空输入框;后续的监听器执行时,输入框的值已经是空字符串,所以会走else分支,看起来就像两个分支同时触发了。
修复方案

方案1:清理重复的事件监听器

在useEffect的返回函数中移除绑定的事件监听器,避免重复挂载:

useEffect(() => {
  const scannerInput = document.getElementById('scannerInput');
  if (!scannerInput) return;

  scannerInput.focus();

  const handleKeyUp = function(event) {
    if(event.key === "Enter"){
      // 先保存输入值,避免清空后逻辑拿不到正确值
      const inputValue = event.currentTarget.value.toString();
      event.currentTarget.value = "";
      
      if (inputValue === ArticleData[randomNumber].artNr.toString()){
        addAmount();
        setContainerAnimation('none');
      } else {
        containerAnimationFunction();
      }
    }
  };

  scannerInput.addEventListener("keyup", handleKeyUp);

  // 组件卸载或依赖更新时移除监听器
  return () => {
    scannerInput.removeEventListener("keyup", handleKeyUp);
  };
}, [amount]);

方案2:改用React受控组件(更推荐)

用state管理输入框的值,符合React数据流规范,彻底避免直接操作DOM带来的问题:

import { useState } from 'react';

// 用state管理输入框内容
const [inputValue, setInputValue] = useState('');

const handleKeyUp = (event) => {
  if(event.key === "Enter"){
    const value = inputValue.toString();
    // 清空输入框
    setInputValue('');
    
    if (value === ArticleData[randomNumber].artNr.toString()){
      addAmount();
      setContainerAnimation('none');
    } else {
      containerAnimationFunction();
    }
  }
};

// 输入框JSX写法
<input
  id="scannerInput"
  value={inputValue}
  onChange={(e) => setInputValue(e.target.value)}
  onKeyUp={handleKeyUp}
  autoFocus
/>

内容的提问来源于stack exchange,提问作者Kron

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 16:05:07