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

React中点击提交按钮后清空输入框的问题

问题分析与解决

你的代码存在状态类型不匹配的问题,导致提交后无法清空输入框:

  1. 初始状态note被设为空字符串'',但change函数中你把它当作对象展开更新,最终note会变成包含notes属性的对象(比如{notes: '输入内容'})。
  2. 提交时用setNotes('')将状态变回字符串,此时textarea绑定的note.notes会变为undefined,React无法正确识别该变化以清空输入框。

修复步骤

  • 统一状态类型:将初始状态改为对象,确保始终以对象类型维护输入内容:
    const [note, setNotes] = React.useState({notes: ''})
    
  • 正确清空状态:在handleSubmit中用对象形式重置状态,匹配当前状态类型:
    function handleSubmit(e) {
        e.preventDefault()  
        addToContainer(note)
        setNotes({notes: ''}) // 用对象形式清空
    }
    

完整修复代码

export default function MainContent() {
    const [note, setNotes] = React.useState({notes: ''})
    const { addToContainer } = React.useContext(notesContext)
    // 注意:原代码中const useRef = React.useRef(null)是错误声明,若未使用可直接删除,如需使用请重命名为inputRef等
    // const inputRef = React.useRef(null)

    function change(e) {
        const { value, name } = e.target
        setNotes(prevNote => {
            return {
                ...prevNote,
                [name] : value
            }    
        })
    }

    function handleSubmit(e) {
        e.preventDefault()  
        addToContainer(note)
        setNotes({notes: ''})
    }

    return (
        <div>
            <div className="main">Here are your notes!</div>
            <form onSubmit={handleSubmit}>
                <textarea 
                    name="notes" 
                    onChange={change} 
                    id="notes" 
                    value={note.notes} 
                />
                <button>Submit here</button>    
            </form>
        </div>
    )    
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 13:08:35