ReactJS Formik动态设置字段值提交时无法传递问题求助
动态计算表单字段提交为空的解决思路
问题原因
你当前通过本地状态inputs更新salesTax值,但react-hook-form的表单状态由库自身管理,本地状态与表单内部状态不同步,导致提交时无法获取到手动更新的salesTax值。
解决步骤
使用react-hook-form的
setValue更新字段
放弃手动维护本地状态,改用库提供的setValue方法同步表单内部状态:// 在SellForm组件中获取setValue const { register, handleSubmit, setValue, formState: { errors } } = useForm({ initialValues, enableReinitialize }); // 修改calculate函数 const calculate = (e) => { const salePrice = parseFloat(e.target.value); if (!isNaN(salePrice)) { const calculatedTax = salePrice * 0.06; // 更新表单内的salesTax字段值 setValue('salesTax', calculatedTax, { shouldValidate: true }); } }移除salesTax字段的手动value绑定
让react-hook-form自动管理字段值,不需要手动设置value={inputs.salesTax}:<FormGroup> <label for="salesTax">Sales Tax</label> <Field name="salesTax" type="number" className="form-control" {...register('salesTax')} /> <ErrorMessage name="salesTax" className="d-block invalid-feedback" component="span" /> </FormGroup>确保表单提交使用handleSubmit包裹
在SellForm中用react-hook-form的handleSubmit处理提交,保证拿到的是同步后的表单值:<form onSubmit={handleSubmit(onSubmit)}> {/* 其他表单字段 */} <FormGroup> <label for="salePrice">Sale Price</label> <Field name="salePrice" type="number" className="form-control" onBlur={(e) => calculate(e)} {...register('salePrice')} /> <ErrorMessage name="salePrice" className="d-block invalid-feedback" component="span" /> </FormGroup> {/* salesTax字段 */} <button type="submit">提交</button> </form>
额外提示
如果需要实时查看字段值,可以使用watch方法:
const salesTax = watch('salesTax'); console.log(salesTax); // 实时获取最新的salesTax值
内容的提问来源于stack exchange,提问作者newmudhar
相关产品推荐
相关产品推荐

