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

React应用中OnKeyDown事件调整日期年份时仅触发一次异常问题排查

问题根因

  • 年份调整的判断区间和你设置的选中区间不匹配:第一次触发年份增减逻辑时,你设置的选中范围是start: 6, end: 10,触发后输入框的光标起始位置selectionStart会变成6,但你写的判断条件是inputEl.current.selectionStart >= 7 && inputEl.current.selectionStart <= 9,6不在这个判断区间内,所以后续按键不会进入年份调整的分支,自然没有响应。
  • 还存在两个潜在问题:
    • cur_date定义在组件外部属于全局变量,多组件实例复用的场景下会出现日期互相干扰的问题
    • 声明的currentDate状态从未被使用,可以直接删除

修复方案

  1. 调整年份的判断区间即可解决只触发一次的问题:
// 把原来的判断条件
// if (inputEl.current.selectionStart >= 7 && inputEl.current.selectionStart <= 9)
// 修改为
if (inputEl.current.selectionStart >= 6 && inputEl.current.selectionStart <= 9)
  1. 建议优化日期存储逻辑,避免全局污染:
    将全局的cur_date移到组件内部,用useState作为组件状态存储,修改日期时同步更新状态,逻辑更稳定:
const DataInput = () => {
  const inputEl = useRef();
  const [selection, setSelection] = useState();
  // 日期作为组件内部状态,删除未使用的currentDate
  const [curDate, setCurDate] = useState(new Date());
  // 初始化日期格式化
  const date_format = curDate
    .toLocaleString()
    .replaceAll(".", "/")
    .replace(",", "");
  const [value, setValue] = useState(date_format);

  // ...其他代码不变

  // 调整年份时的逻辑示例
  if (inputEl.current.selectionStart >= 6 && inputEl.current.selectionStart <= 9) {
    setSelection({ start: 6, end: 10 });
    const newYear = new Date(curDate);
    newYear.setFullYear(newYear.getFullYear() + 1);
    setCurDate(newYear);
    setValue(
      newYear.toLocaleString()
        .replaceAll(".", "/")
        .replace(",", "")
    );
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 06:06:07