预填充React Formik表单可以通过以下步骤完成:
import { Formik, Field, Form } from 'formik';
const initialValues = {
name: '',
email: '',
password: '',
};
<Formik initialValues={initialValues} onSubmit={handleSubmit}>
{/* 表单内容 */}
</Formik>
<Field name="name" type="text" />
<Field name="email" type="email" />
<Field name="password" type="password" />
<Field name="name" type="text" initialValue="John Doe" />
const handleSubmit = (values) => {
console.log(values);
// 执行表单提交逻辑
};
import React from 'react';
import { Formik, Field, Form } from 'formik';
const initialValues = {
name: '',
email: '',
password: '',
};
const handleSubmit = (values) => {
console.log(values);
// 执行表单提交逻辑
};
const MyForm = () => (
<Formik initialValues={initialValues} onSubmit={handleSubmit}>
<Form>
<label htmlFor="name">Name:</label>
<Field name="name" type="text" />
<label htmlFor="email">Email:</label>
<Field name="email" type="email" />
<label htmlFor="password">Password:</label>
<Field name="password" type="password" />
<button type="submit">Submit</button>
</Form>
</Formik>
);
export default MyForm;
这样,当你渲染MyForm组件时,表单字段将自动填充为初始值。你可以根据需要修改initialValues对象中的值来预填充不同的表单字段。
领取专属 10元无门槛券
手把手带您无忧上云