Axi*_*ili 5 forms reactjs formik
在Formik中,如何使“重置”按钮仅在确认后才重置表单?
即使您单击取消,下面的我的代码仍会重置表单。
var handleReset = (values, formProps) => {
return window.confirm('Reset?'); // still resets after you Cancel :(
};
return (
<Formik onReset={handleReset}>
{(formProps) => {
return (
<Form>
...
<button type='reset'>Reset</button>
</Form>
)}}
</Formik>
);
Run Code Online (Sandbox Code Playgroud)
小智 14
如果使用useFormik钩子,则formik.resetForm()在 onClick 事件上使用,或者如果您使用的是<Formik>组件,则可以这样做:
onSubmit={(values, { setSubmitting, resetForm }) => {
// your code
resetForm();
}}
Run Code Online (Sandbox Code Playgroud)
我不完全确定,但我认为您将不得不编写自己的重置功能,而无需带reset类型的按钮。像这样的东西:
const handleReset = (resetForm) => {
if (window.confirm('Reset?')) {
resetForm();
}
};
function Example() {
return (
<Formik initialValues={{ value: 1 }}>
{formProps => {
return (
<Form>
<Field name="value" type="number" />
<button
onClick={handleReset.bind(null, formProps.resetForm)}
type="button"
>
Reset
</button>
</Form>
);
}}
</Formik>
);
}
Run Code Online (Sandbox Code Playgroud)
如果你真的想使用onReset,我认为唯一的方法就是抛出错误。Formik源代码似乎表明resetForm()无论您的onReset()函数返回什么都会被调用。
const handleReset = () => {
if (!window.confirm('Reset?')) {
throw new Error('Cancel reset');
}
};
function Example() {
return (
<Formik initialValues={{ value: 1 }} onReset={handleReset}>
{formProps => {
return (
<Form>
<Field name="value" type="number" />
<button type="reset">
Reset
</button>
</Form>
);
}}
</Formik>
);
}
Run Code Online (Sandbox Code Playgroud)
尽管就个人而言,我仍然会采用第一个解决方案。
您好,您可以resetForm在onSubmit中使用@Aximili 。
onSubmit={(values, { resetForm }) => {
// do your stuff
resetForm();
}}
Run Code Online (Sandbox Code Playgroud)
该怎么resetForm办?
必须重设表格。这将清除并触摸错误,将isSubmitting设置为false,将isValidating设置为false,然后使用当前WrappedComponent的prop或作为参数传递的内容重新运行mapPropsToValues。后者对于在componentWillReceiveProps中调用resetForm很有用。
小智 7
2023 年,
formik.resetForm();这对我有用。
onSubmit这是事件的完整代码
onSubmit:(values)=>{
const name = values.name;
const mobile = values.mobile;
const website = values.website;
const service = values.service;
const msg = values.msg;
axios.post('/api/SendContactForm', {name, mobile, website, service, msg})
.then(function (response) {
//console.log(response);
toast.success(' Thanks for the message. We will contact you asap.');
formik.resetForm();
})
.catch(function (error) {
console.log(error);
formik.resetForm();
toast.error(error.message || error.statusText);
});
}
});
Run Code Online (Sandbox Code Playgroud)
我知道 OP 的问题是针对Formik.
但是,对于任何使用useFormik钩子并希望在“重置”按钮单击时清除表单的人来说,这是实现这一目标的一种方法。
<button type="reset" onClick={ e => formik.resetForm()}> Reset</button>
| 归档时间: |
|
| 查看次数: |
5267 次 |
| 最近记录: |