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

React学习求助:输入框每次输入后自动失焦问题排查

React输入框输入后失去焦点问题解决

问题原因

你将Row组件定义在了MultiplierBox组件内部,每次MultiplierBox因状态更新(输入触发setA)重新渲染时,Row会被重新定义为全新的组件类型。React会判定这是不同的组件,卸载旧输入框DOM并挂载新的,导致焦点丢失。

解决方案

将Row组件移至MultiplierBox外部,避免其随父组件重渲染被反复重新定义,并将更新函数updateA作为props传入Row:

// 将Row组件移到外部
function Row({ a, index, updateA }) {
  function handleA(event) {
    const newValue = parseFloat(event.target.value)
    updateA(index, newValue)
  }
  return <input type="number" value={a[index]} onChange={handleA} />
}

function MultiplierBox() {
  const [a, setA] = useState([1.0, 2.2])
  
  function updateA(index, newValue) {
    const newArray = [...a];
    newArray[index] = newValue;
    setA(newArray);
  }
  
  return (
    <div className="MultiplierBox">
      {a}
      <Row a={a} index={0} updateA={updateA} />
      <Row a={a} index={1} updateA={updateA} />
    </div>
  );
}

补充说明

你之前用单个值替代数组有效,本质是当时没有抽离Row组件,输入框直接在父组件内渲染,不会触发组件类型的重新创建,因此焦点能保持。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 23:20:16