React预算追踪应用:提交表单后自动清空的实现问题
Solution
To automatically clear the form after submitting an expense, call your reset() function right after dispatching the ADD_EXPENSE action in the onSubmit handler. This ensures the expense is added first, then the form fields are reset to empty values.
Additionally, fix the for attribute on your labels to htmlFor (since for is a reserved keyword in JavaScript, React uses htmlFor instead to avoid conflicts and accessibility issues).
Here's the corrected code:
import React, { useContext, useState } from 'react'; import { AppContext } from '../context/AppContext'; import { v4 as uuidv4 } from 'uuid'; const AddExpenseForm = () => { const { dispatch } = useContext(AppContext); const [name, setName] = useState(''); const [cost, setCost] = useState(''); const onSubmit = (event) => { event.preventDefault(); const expense = { id: uuidv4(), name: name, cost: parseInt(cost), }; dispatch({ type: 'ADD_EXPENSE', payload: expense, }); // Reset form fields after submitting reset(); }; const reset = () => { setName(''); setCost(''); } return ( <form onSubmit={onSubmit}> <div className='row'> <div className='col-sm'> <label htmlFor='name'>Name</label> <input required='required' type='text' className='form-control' id='name' value={name} onChange={(event) => setName(event.target.value)} ></input> </div> <div className='col-sm'> <label htmlFor='cost'>Cost</label> <input required='required' type='text' className='form-control' id='cost' value={cost} onChange={(event) => setCost(event.target.value)} ></input> </div> <div className='col-sm'> <button type='submit' className='btn btn-primary mt-3'> Save </button> <button type='reset' className='btn btn-warning mt-3' onClick={reset}>Reset</button> </div> </div> </form> ); }; export default AddExpenseForm;
Key Notes:
- The
dispatchaction updates your context with the new expense, refreshing the budget totals and expense list. - Calling
reset()immediately after dispatch clears the controlled input fields by resetting their associated state variables. - The
htmlForfix resolves potential React warnings and maintains proper label-input association for accessibility.
内容的提问来源于stack exchange,提问作者John Nelson
相关产品推荐
相关产品推荐

