我希望有人能帮我。
我已经用Formik创建了一个抽象的可重用表单组件,除了一个问题我似乎不能弄清楚之外,它工作得非常好。
这是我的可重用表单组件
export const Form = (props: any) => {
const { children, initialValues, onSubmit, schema, formStyles, buttonText, buttonStyles } =
props;
const handleSubmit = (values: any, actions: any) => {
onSubmit(values, actions);
};
return (
<Formik initialValues={initialValues} onSubmit={handleSubmit} validationSchema={schema}>
{(formikProps: any) => {
const { handleSubmit, isSubmitting, isValid, dirty } = formikProps;
return (
<form className={formStyles} onSubmit={handleSubmit}>
{children}
<div className="pt-5">
<div className="flex justify-start">
<Button
className={buttonStyles}
type="submit"
isLoading={isSubmitting}
disabled={!isValid || !dirty}
>
{buttonText}
</Button>
</div>
</div>
</form>
);
}}
</Formik>
);
};
这是使用上述组件的示例表单
const ExampleForm = () => {
return (
<Form
initialValues={initialValues}
onSubmit={(values: any, actions: any) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
actions.setSubmitting(false);
}, 1000);
}}
schema={schema}
buttonText="Submit"
>
<div className="mt-6 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-6">
<InputField
type="text"
label="First name"
name="firstName"
placeholder="First name"
/>
<InputField type="text" label="Last name" name="lastName" placeholder="Last name" />
<InputField
type="email"
label="Email address"
name="email"
placeholder="Email address"
width="col4"
/>
</div>
</Form>
);
};
目前,除了在表单组件中有一个硬编码的提交按钮之外,这种方法运行良好。
有人能帮我吗?
1条答案
按热度按时间x9ybnkn61#
你可以用
children
传递formikProps
绑定。然后,您可以在孩子上访问此内容: