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

React独立Input组件提交后无法清空值的问题求助

React子组件Input清空后输入框仍保留内容的问题解决

问题核心

提交表单后父组件inputs状态已控制台确认清空,但Input子组件的输入框仍显示原有内容,本质是输入框未与父组件状态做受控绑定,属于非受控组件,DOM自身维护输入值,不受React状态驱动。

问题分析

  1. Input子组件内的inn状态完全未使用,输入框未设置value属性,无法响应父组件状态变化;
  2. 父组件内冗余的useEffect无意义,仅在content为空时重复设置空状态;
  3. dataSubmit函数内重复调用setInputs({ content: "" }),逻辑冗余。

修复方案

步骤1:改造Input组件为受控组件

移除无用的局部状态,给输入框添加value属性绑定父组件传入的值,同时修正JSX语法错误(for→htmlFor、class→className):

import { useState } from "react";

const Input = (props) => {
  return (
    <div className="flex w-full p-5 justify-center items-center mx-auto gap-4 ">
      {props.title ? (
        <label 
          htmlFor="helper-text"
          className={`block mb-1 w-[10%] text-xl text-gray-900 dark:text-white gap-5 ${props.classes}`}
        >
          {props.title}
        </label>
      ) : ""}

      <input
        onChange={props.fn}
        type={props.type}
        id="helper-text"
        value={props.value}
        aria-describedby="helper-text-explanation"
        className={`bg-gray-50 border border-gray-300 w-[50%] text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 ${props.classes}`}
        placeholder={`Enter Your Valid ${props.name}`}
      />
    </div>
  )
}

export default Input;

步骤2:优化父组件逻辑

给Input组件传递value参数,删除冗余useEffect,简化dataSubmit内的清空逻辑:

import React, { useState } from 'react'
import Button from '../../components/Button'
import Input from '../../components/Input'
import toast from 'react-hot-toast'

const AddTask = () => {
  const [inputs, setInputs] = useState({ content: "" })

  const dataSubmit = async (data) => {
    console.log(data)

    try {
      if (data.content.trim() === "") {
        toast.error("Please Enter a Valid Task")
        return
      }
      const res = await fetch(
        "http://localhost:3000/api/v1/users/add-todo",
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(data),
          credentials: "include"
        }
      )
      const response = await res.json()
      console.log(response)
      
      response.statusCode === 200 
        ? toast.success("Task Added Successfully")
        : toast.error(`Something Went Wrong : ${response.message}`)
      
      setInputs({ content: "" })
    } catch (error) {
      console.log("Error : ", error)
      toast.error(`Something Went Wrong: ${error}`)
      setInputs({ content: "" })
    }
  }

  return (
    <div>
      <form className="w-[60%] mt-20 mx-auto flex justify-center items-center flex-col">
        <div>
          <h1 className="text-3xl text-center font-bold mb-5">Add Task</h1>
        </div>

        <Input
          classes='w-full h-12 m-[0px]'
          name="click here to write task"
          type="text"
          value={inputs.content}
          fn={(e) => setInputs({ content: e.target.value })}
        />
    
        <Button
          fn={(e) => {
            e.preventDefault()
            dataSubmit(inputs)
          }}
          title="Add Task"
          classes="hover:bg-green-400 bg-zinc-600 flex text-center justify-center mt-5 mx-auto h-12 w-24"
        />
      </form>
    </div>
  )
}

export default AddTask

核心原理

React受控组件通过value绑定状态,onChange事件更新状态,实现状态与输入框内容双向同步。当父组件清空状态时,子组件输入框的value同步为空,从而显示清空后的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 09:13:11