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

React中JSX输入框无法修改,如何更新features_dict状态并发起HTTP请求

问题解决:React输入框无法修改及状态更新方案

问题根源

  1. 输入框作为受控组件,未绑定onChange事件,无法触发状态更新,导致输入无响应
  2. 组件内变量名错误:定义的listFeaturesElement在渲染时误写为listIngredientsElement
  3. 表格结构不符合规范:每个特性条目用<tbody>包裹,正确应该用<tr>表示表格行
  4. map循环未添加唯一key属性,会触发React性能警告

修改后的代码实现

App组件

import { useState } from 'react';
import { FeaturesDetail } from './FeaturesDetail';

export function App() {
  // 初始状态由HTTP请求加载,这里模拟示例数据
  const [features_dict, set_features_dict] = useState({
    "features": [
      { id: 1, name: "特性A", price: 100 },
      { id: 2, name: "特性B", price: 200 }
    ]
  });

  // 更新单个特性价格的方法
  const updateFeaturePrice = (featureId, newPrice) => {
    set_features_dict(prev => ({
      ...prev,
      features: prev.features.map(feature => 
        feature.id === featureId 
          ? { ...feature, price: Number(newPrice) } 
          : feature
      )
    }));
  };

  // 发送HTTP请求更新后端的方法
  const submitToBackend = async () => {
    try {
      await fetch('/api/update-features', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(features_dict),
      });
      // 请求成功后的处理,比如提示用户
      alert("配置已更新");
    } catch (error) {
      console.error("更新失败:", error);
      alert("更新失败,请重试");
    }
  };

  return (
    <div className={s.main_container}>
      <FeaturesDetail 
        FeaturesDict={features_dict} 
        onUpdatePrice={updateFeaturePrice}
        onSubmit={submitToBackend}
      />
    </div>
  );
}

FeaturesDetail组件

export function FeaturesDetail({ FeaturesDict, onUpdatePrice, onSubmit }) {
  const listFeaturesElement = FeaturesDict.features.map(feature => (
    <tr key={feature.id}>
      <td>{feature.name}</td>
      <td>
        <input
          type="number"
          value={feature.price}
          onChange={(e) => onUpdatePrice(feature.id, e.target.value)}
        />
      </td>
    </tr>
  ));

  return (
    <div>
      <table>
        <thead>
          <tr>
            <td>Name</td>
            <td>Price</td>
          </tr>
        </thead>
        <tbody>
          {listFeaturesElement}
        </tbody>
      </table>
      <button onClick={onSubmit}>Update All</button>
    </div>
  );
}

关键修改说明

  • 受控输入绑定:给输入框添加onChange事件,调用父组件传递的onUpdatePrice方法更新对应特性的价格,确保状态与输入值同步
  • 状态更新逻辑:使用函数式更新set_features_dict(prev => ...),避免状态更新依赖旧值的问题
  • 表格结构修正:用<tr>包裹每个特性的单元格,所有行放在同一个<tbody>内,符合HTML表格规范
  • HTTP请求处理:在App组件中实现submitToBackend方法,将最新的features_dict通过POST请求发送到后端,处理成功/失败的情况
  • 变量名修正:将渲染时的变量名改为正确的listFeaturesElement

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 23:57:27