Formik复选框的值为true时未显示选中状态

3
我正在使用Material-UI/Stepper和Formik技术,但在显示一个状态为true的复选框时遇到了问题。
在我的表格中,我正在使用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 - Shyam
@Shyam - 这个问题不在于 Formik 状态值,因为它被正确地设置为 true。问题是,当我前进一步然后返回一步时,复选框中的勾号会消失。尽管值仍然为 true,但勾号不再显示。 - ArthurJ
1
当您在CheckboxWrapper中控制台记录field.checked时,会得到什么? - Shyam
@Shyam - 我得到了 undefined,但是我的 formik 名称值,在我使用 <Checkboc/> 时被设置为 true。有什么想法可以在复选框的 formik 状态值为 true 时保持勾选状态吗? - ArthurJ
@Shyam - 找到了解决方法。请看“回答你的问题”。 - ArthurJ
1个回答

0
解决方案是使用:checked={field.value}以保持复选框中的勾选状态。
  return (
    <FormControl {...configFormControl}>
      <FormLabel component="legend">{legend}</FormLabel>
      <FormGroup>
        <FormControlLabel
          control={<Checkbox {...configCheckbox} />}
          label={label}
          checked={field.value}
        />
      </FormGroup>
    </FormControl>
  );

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接