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

React中点击提交按钮后如何清除输入框内容?

问题解决:提交后输入框视觉未清空的处理

问题描述

点击<button type="submit" className="btn btn-primary">Create</button>按钮成功创建英雄卡片后,调用.then(() => clearFields())能清空字段逻辑(再次点击会生成空白卡片),但输入框视觉上仍显示原有内容,需要实现点击提交后输入框同步清空。

问题原因

你的输入控件只绑定了onChange事件更新状态,但没有绑定value属性与状态变量关联。React中受控组件需要同时通过value和onChange实现状态与视图的双向同步,否则状态更新后视图不会自动刷新。

另外代码存在Promise链错误:then(dispatch(heroCreate(newHero)))会直接执行dispatch,而非等待请求成功后执行,可能导致状态更新时机异常。

解决方案

  1. 给所有输入控件添加value属性,绑定对应的state变量:
    • 姓名输入框:添加value={name}
    • 描述文本框:添加value={description}
    • 元素选择框:添加value={element},同时给默认选项设置value=""匹配初始空状态
  2. 修正Promise链中的dispatch调用,将其包裹在函数中,确保请求成功后再分发action:.then(() => dispatch(heroCreate(newHero)))

修改后的完整代码

import { useState } from "react";
import { v4 as uuidv4 } from 'uuid';
import { useDispatch } from 'react-redux';
import { heroCreate } from '../../actions';
import { useHttp } from '../../hooks/http.hook';

const HeroesAddForm = () => {
    const [name, setName] = useState('');
    const [description, setDescription] = useState('');
    const [element, setElement] = useState('');
    const {request} = useHttp();

    const dispatch = useDispatch();

    const clearFields = () => {
        setName('');
        setDescription('');
        setElement('');
    }
    
    const handleSubmit = (event) => {
        event.preventDefault();

        const newHero = {
            id: uuidv4(),
            name: name,
            description: description,
            element: element
        };
        
        request("http://localhost:3001/heroes", "POST", JSON.stringify(newHero))
        // 修正:确保请求成功后再分发action
        .then(() => dispatch(heroCreate(newHero)))
        .then(() => clearFields())
        .catch(err => console.log(err));   
    }
    
    return (
        <form className="border p-4 shadow-lg rounded" onSubmit={handleSubmit}>
            <div className="mb-3">
                <label htmlFor="name" className="form-label fs-4">Name of new hero</label>
                <input
                    required
                    type="text"
                    name="name"
                    className="form-control"
                    id="name" 
                    onChange={event => setName(event.target.value)}
                    value={name}
                    placeholder="What is your name?" />
            </div>

            <div className="mb-3">
                <label htmlFor="text" className="form-label fs-4">Description</label>
                <textarea
                    required
                    name="text"
                    className="form-control"
                    id="text" 
                    placeholder="Tell us something about your hero"
                    onChange={event => setDescription(event.target.value)}
                    value={description}
                    style={{ "height": '130px' }} />
            </div>

            <div className="mb-3">
                <label htmlFor="element" className="form-label">Choose hero element</label>
                <select
                    required
                    className="form-select"
                    id="element"
                    onChange={event => setElement(event.target.value)}
                    value={element}
                    name="element">
                    <option value="">I have the element of...</option>
                    <option value="fire">Fire</option>
                    <option value="water">Water</option>
                    <option value="wind">Wind</option>
                    <option value="earth">Earth</option>
                </select>
            </div>

            <button type="submit" className="btn btn-primary">Create</button>
        </form>
    )
}

export default HeroesAddForm;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 14:37:56