Formik React 使用 2 个按钮(提交和保存)提交表单 - 保存按钮不触发验证

Formik React with 2 buttons (Submit and Save) to submit form - Save button not to trigger validation

Formik 很新,我有一个简单的表单,它有验证。我需要有 2 个按钮,提交和一个保存按钮,它们主要做同样的事情,但是,如果单击 "Save" 按钮,我希望验证为 "disabled" 或者更确切地说,所有必填字段都将不再需要。有什么想法可以实现吗?

下面的一些代码:

const initialValues = {
    title: "",
    description: ""
};

const validationSchema = Yup.object().shape({
        title: Yup.string()
            .max(50, 'You may only enter up to 50 characters')
            .required('Required'),
        description: Yup.string()
            .max(200, 'You may only enter up to 200 characters')
            .required('Required'),
        })


const CreateForm = () => {

    const handleCancel = () => {
        alert("Cancelled!")
    }

    return (
        <div>
            <Formik initialValues={initialValues}
                validationSchema={validationSchema}
                onSubmit={(values) => {
                    setTimeout(() => {
                        alert(JSON.stringify(values, null, 2));
                    }, 3000)
                }}
            >
                {props => (
                    <Form>
                        <CustomTextInput label="Title"
                            name="title" type="input" placeholder="Enter Title" />

                        <CustomTextInput label="Description"
                            name="description" type="input" placeholder="Description" />

                        <div>
                            <Button type="submit" variant="contained" color="primary">
                                Submit
                            </Button> &nbsp;
                            <Button type="submit" variant="contained" color="secondary" >
                                Save
                            </Button>&nbsp;
                            <Button variant="contained" color="default" onClick={handleCancel}>
                                Cancel
                            </Button>
                        </div>
                    </Form>
                )}
            </Formik>
        </div>
    )
}

export default CreateForm

首先删除type="submit"。因为 formik 会像提交一样理解它并验证它。第二个添加onClick功能:

<Button
  variant="contained"
  color="secondary"
  onClick={() => handleSave(props.values)} >Save</Button>

并且:

const handleSave = (values) => {
  // do what you want like on submit
}