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

React Table自定义输入框值消失 如何绑定状态设置value属性

问题根因

输入框属于React受控组件,你只实现了onChange更新状态的逻辑,但没有给输入框绑定对应状态值作为value属性:每次输入触发itemQuantity更新后,组件重渲染时输入框拿不到已存储的数量值,就会重置为空,造成输入内容"消失"的现象。

修复方案
  • 在数量列的Cell渲染函数中,以商品唯一标识code为匹配键,从itemQuantity数组中查找当前行商品对应的已保存数量
  • 给<input>标签绑定value属性,未匹配到已存数量时默认传空字符串,避免React受控/非受控组件切换的警告
  • (可选优化)将handleQuantites改为函数式更新写法,避免状态更新时的闭包陈旧值问题

修复后代码参考

状态定义部分保持原有逻辑即可:

const [itemQuantity,setItemQuantity] = useState([]);

优化后的数量更新方法+列配置代码:

const handleQuantites = (newValue) => {
  // 函数式更新避免闭包拿到旧的itemQuantity值
  setItemQuantity(prevItems => {
    const existIndex = prevItems.findIndex(item => item.code === newValue.code);
    // 已存在对应商品则更新数量
    if (existIndex > -1) {
      const newItems = [...prevItems];
      newItems[existIndex].Quantity = newValue.Quantity;
      return newItems;
    }
    // 不存在则新增数量条目
    return [...prevItems, newValue];
  })
};

const BundleColums = useMemo(
  () => [
    {
      Header: "Bundle Name",
      accessor: "name",
    },
    {
      Header: "Bundle Category",
      accessor: "categoryName",
    },
    {
      Header: "Bundle Status",
      accessor: "status",
    },
    {
      Header: "Quantity",
      accessor:"Quantity",
      Cell: ({ cell }) => {
        // 从状态中匹配当前行商品的已输入数量
        const currentItem = itemQuantity.find(item => item.code === cell.row.original.code);
        const currentValue = currentItem?.Quantity ?? '';
        return (
          <Fragment>
            <input
              type={"text"}
              placeholder="Add Quantity"
              className="form-control"
              // 绑定value属性实现受控渲染
              value={currentValue}
              onChange={(e) => {
                handleQuantites({
                  ...cell.row.original,
                  Quantity: e.target.value,
                });
              }}
              min={0}
            />
          </Fragment>
        )
      },
    },

    {
      Header: "Actions",
      Cell: ({ cell }) => (
        <Fragment>
          <button
            className="btn btn-primary "
            onClick={() => {
              handleAddToCart(cell.row.original);
            }}
          >
            Add to Cart
          </button>
        </Fragment>
      ),
    },
  ],
  [itemQuantity, handleQuantites]
);
注意事项
  • 必须保证商品的code字段为全局唯一值,否则会出现不同商品输入框值串扰的问题
  • 如果需要限制输入为纯数字,可以将input的type改为number,同时在onChange回调中增加数字格式校验
  • 调用handleAddToCart时,如果要获取用户输入的最新数量,优先从itemQuantity状态中匹配对应商品的Quantity值,不要直接使用cell.row.original上的初始数据

若出现ESLint依赖警告,可以将handleQuantites用useCallback包裹,避免函数每次渲染重新创建导致列配置不必要的重计算。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 12:51:24