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

disabled属性导致input的onChange无法触发,无法更新state求助

问题原因

浏览器默认会阻止**禁用(disabled)**的表单元素触发任何用户交互事件,包括onChange,所以你的handleChangeLevel3函数完全不会执行,自然无法将拼接后的值同步到inputList state中。

解决方案

方案1:用readOnly替代disabled

将输入框的disabled属性替换为readOnly,输入框依然保持不可编辑状态,但可以触发onChange事件(用户无法手动修改值,仅适配代码驱动的value更新场景):

<input
  className="form-control"
  type="text"
  name="xero_code"
  onChange={(e) =>
    handleChangeLevel3(
      e,
      i,
      index,
      "product_information",
      "order_list_products"
    )
  }
  value={
    spreadList.machine +
    "" +
    data.product_name +
    "" +
    spreadList.spreadRate +
    "." +
    spreadList.location
  }
  placeholder="Xero Code"
  readOnly 
/>

方案2:监听依赖变量变化,主动更新state

输入框的value由spreadList和data.product_name拼接生成,直接用useEffect监听这两个变量的变化,当它们更新时主动修改inputList中对应的xero_code字段,无需依赖onChange:

import { useEffect } from 'react';

// 在组件内部添加该监听逻辑
useEffect(() => {
  const xeroCodeValue = `${spreadList.machine}${data.product_name}${spreadList.spreadRate}.${spreadList.location}`;
  setDirty();
  // 注意:如果是多层嵌套对象,浅拷贝可能不够,需用深拷贝(比如JSON.parse(JSON.stringify(inputList)))
  const updatedList = { ...inputList };
  updatedList.product_information[i].order_list_products[index].xero_code = xeroCodeValue;
  setInputList(updatedList);
  handleXeroCode();
}, [spreadList, data.product_name, i, index, inputList]); // 务必添加所有依赖项

此方案可保留disabled属性,因为无需依赖输入框交互事件更新state。

额外注意点

  • 不要同时设置value和defaultValue,这会导致受控组件与非受控组件逻辑冲突,直接移除defaultValue即可。
  • 若使用方案2,多层嵌套的inputList需做深拷贝,避免浅拷贝导致的state更新异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 12:50:28