我正在使用Material-UI/Stepper和Formik技术,但在显示一个状态为true的复选框时遇到了问题。
在我的表格中,我正在使用Material-UI Stepper。我面临的问题是,在我的表格第1页上,我使用了一个复选框(FormControlLabel API)。当我单击复选框时,这个复选框的formik状态值为true,但当我前进到下一页然后按返回按钮返回到包含复选框的第一页时,formik状态值仍保持true,但我的复选框不再被选中。
以下是我用于渲染复选框的代码,但我不知道为什么这个复选框没有显示为已选中:
我在FormControlLabel API中添加了代码```checked={field.checked}```,但没有任何影响。
我在实际表单中调用上述代码的方式如下:
在我的表格中,我正在使用Material-UI Stepper。我面临的问题是,在我的表格第1页上,我使用了一个复选框(FormControlLabel API)。当我单击复选框时,这个复选框的formik状态值为true,但当我前进到下一页然后按返回按钮返回到包含复选框的第一页时,formik状态值仍保持true,但我的复选框不再被选中。
以下是我用于渲染复选框的代码,但我不知道为什么这个复选框没有显示为已选中:
我在FormControlLabel API中添加了代码```checked={field.checked}```,但没有任何影响。
import React from 'react';
import {
Checkbox,
FormControl,
FormControlLabel,
FormGroup,
FormLabel
} from '@material-ui/core';
import { useField, useFormikContext } from 'formik';
const CheckboxWrapper = ({
name,
label,
legend,
...otherProps
}) => {
const { setFieldValue } = useFormikContext();
const [field, meta] = useField(name);
const handleChange = evt => {
const { checked } = evt.target;
setFieldValue(name, checked);
};
const configCheckbox = {
...field,
onChange: handleChange
};
const configFormControl = {};
if (meta && meta.touched && meta.error) {
configFormControl.error = true;
}
return (
<FormControl {...configFormControl}>
<FormLabel component="legend">{legend}</FormLabel>
<FormGroup>
<FormControlLabel
control={<Checkbox {...configCheckbox} />}
label={label}
checked={field.checked}
/>
</FormGroup>
</FormControl>
);
};
export default CheckboxWrapper;
我在实际表单中调用上述代码的方式如下:
<Checkbox
name="termsAgreement"
label="I agree"
/>
其中name="termsAgreement"
是我的 Formik 初始状态值。
非常感谢您的帮助。
field.checked
在这里不起作用。文档说你需要传递一个对象给 useField 来访问 checked 属性。尝试将传递给 useField 的参数更改为{ name, type: 'checkbox' }
。https://formik.org/docs/api/useField#fieldinputpropsvalue - Shyamundefined
,但是我的 formik 名称值,在我使用<Checkboc/>
时被设置为 true。有什么想法可以在复选框的 formik 状态值为 true 时保持勾选状态吗? - ArthurJ