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

React基础表单问题:输入框无法录入内容且提交无值

问题分析与解决方案

嘿,我一眼就发现你代码里的核心问题了——你把setState当成普通属性赋值了,但它其实是React组件用来更新状态的方法!

错误根源

在你的changeHandler函数里,这段代码是完全错误的:

this.setState = { [e.target.name]: e.target.value };

setState不是一个可以直接赋值的属性,而是需要调用的方法。你这样写不仅不会更新组件状态,还会把React内置的setState方法给覆盖掉,直接导致状态完全无法更新——这就是为什么输入框看起来可编辑,但输入的内容根本存不到状态里,提交时也拿不到任何值的原因。

修正后的完整代码

只需要把changeHandler改成正确调用setState的形式就可以解决问题:

import React, { Component } from "react";
class Postform extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "",
      category: "",
      price: "",
    };
  }
  // 修正这里的setState调用方式
  changeHandler = (e) => {
    this.setState({ [e.target.name]: e.target.value });
  };
  submitHandler = (e) => {
    e.preventDefault();
    console.log(this.state);
  };
  render() {
    const { name, category, price } = this.state;
    return (
      <div>
        <form onSubmit={this.submitHandler}>
          <div>
            <input type="text" name="name" placeholder="Name" value={name} onChange={this.changeHandler} />
            <input type="text" name="category" placeholder="Category" value={category} onChange={this.changeHandler} />
            <input type="text" name="price" placeholder="Price" value={price} onChange={this.changeHandler} />
          </div>
          <button type="submit">Add product</button>
        </form>
      </div>
    );
  }
}
export default Postform;

效果验证

修正后,当你在输入框输入内容时,changeHandler会触发并调用setState更新对应字段的状态,输入框的value会同步显示最新的状态值;点击提交按钮时,console.log(this.state)就能正常打印出你输入的所有内容了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 21:02:54