材质ui滑块组件onChange事件无法与Fromik handleChange事件一起使用

时间:2020-05-29 06:02:25

标签: reactjs material-ui formik yup

初始甲酸值由滑块获取,但Formik handleChange事件不会更新滑块值

Formik函数

const formik = useFormik({
        initialValues: {
            slide: 50,
        },
        validationSchema: Yup.object({
            slide: Yup.number()
                .min(100, 'must be grater than 100'),
        }),
        onSubmit: values => {
            alert(JSON.stringify(values, null, 2));
        },
    });

具有onChange事件的材质ui滑块组件,它将获得初始formik值,但不会更新

<Slider
    name="slide"
    id="slide"
    valueLabelDisplay="auto"
    aria-label="term slider"
    defaultValue={formik.values.slide}
    onChange={formik.handleChange}
    min={1}
    max={110}
  />

Please check the codesandbox sample

1 个答案:

答案 0 :(得分:0)

您可以使用 setFieldValue

import React from "react";
import "./styles.css";
import Slider from "@material-ui/core/Slider";
import { useFormik } from "formik";
import * as Yup from "yup";
import Button from "@material-ui/core/Button";
import { Formik } from "formik";

export default function App() {
  return (
    <div>
      <Formik
        initialValues={{ slide: 50 }}
        validationSchema={Yup.object({
          slide: Yup.number().min(50, "must be grater than 100")
        })}
        onSubmit={(values, { setSubmitting }) => {
          setTimeout(() => {
            alert(JSON.stringify(values, null, 2));
            setSubmitting(false);
          }, 400);
        }}
      >
        {({
          values,
          errors,
          touched,
          handleChange,
          handleBlur,
          handleSubmit,
          isSubmitting,
          setFieldValue
          /* and other goodies */
        }) => (
          <form onSubmit={handleSubmit}>
            <Slider
              name="slide"
              id="slide"
              valueLabelDisplay="auto"
              aria-label="term slider"
              value={values.slide}
              onChange={(e, v) => {
                setFieldValue('slide', v);
              }}
              min={1}
              max={110}
            />
            {errors.slide && touched.slide && errors.slide}
            <button type="submit" disabled={isSubmitting}>
              Submit
            </button>
          </form>
        )}
      </Formik>
    </div>
  );
}