我想在使用formik订餐项目中实现一个用于验证有效性的检查表单,但是我遇到了创建两个按钮的问题。无论点击哪个按钮,都会调用handleSubmit。我该如何解决这个问题?
函数goBack只是将状态设置为false。
export default function Checkout(props) {
function handleSubmit(event) {
// event.preventDefault();
console.log("Hello");
}
return (
<Formik
initialValues={{ userName: "Hi", street: "", postalCode: "", city: "" }}
onSubmit={handleSubmit}
>
{(props) => (
<Form className={styles["form"]}>
<div className={styles["form-control"]}>
<div className={styles["form-control__input"]}>
<label htmlFor="userName">Your name</label>
<Field type="text" name="userName" id="userName"></Field>
</div>
<div className={styles["form-control__input"]}>
<label htmlFor="street">Street</label>
<Field type="text" name="street" id="street"></Field>
</div>
<div className={styles["form-control__input"]}>
<label htmlFor="postalCode">Postal code</label>
<Field type="text" name="postalCode" id="postalCode"></Field>
</div>
<div className={styles["form-control__input"]}>
<label htmlFor="city">City</label>
<Field type="text" name="city" id="city"></Field>
</div>
</div>
<div className={styles["form-actions"]}>
<CloseButton type="button" onClick={props.goBack}>Back</CloseButton>
<OrderButton type="submit">Confirm</OrderButton>
</div>
</Form>
)}
</Formik>
);
}
export default function CloseButton(props) {
return <button type={props.type} onClick={props.onClick} className={styles["close-button"]}>{props.children}</button>;
}
export default function OrderButton(props) {
return <button type={props.type} onClick={props.onClick} className={styles['order-button']}>{props.children}</button>
}
我希望CloseButton关闭表单并返回到订单列表,但它只调用由Formik组件创建的handleSubmit,而不是props中的函数。我阅读了文档,但关于使用两个按钮创建formik的内容以及与我的问题相关的内容都没有提到。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
看起来在
props.goBack中,你想引用组件的props,但实际上使用的是 Formik 内部的props(因为它是最近的props声明)。由于 Formik 的 props 上没有定义goBack,所以你将undefined作为onClick处理程序传递给按钮。解决这个问题最直接的方法是重命名其中一个 props 变量,我建议将 Formik 的 props 命名为
formikProps或类似的名称。在我看来,更好的方法是解构 props(在这两种情况下,虽然只有一种是必要的),像这样:
export default function Checkout({ goBack }) { // ... return ( <Formik> {(props) => ( // ... <CloseButton type="button" onClick={goBack}>Back</CloseButton> // ... )} </Formik> ) }