初始甲酸值由滑块获取,但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}
/>
答案 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>
);
}