【问题标题】:Checkbox when clicked does not show text fields. collapse not working单击时的复选框不显示文本字段。崩溃不工作
【发布时间】:2022-11-19 20:56:49
【问题描述】:

我有这个复选框,当它被点击时不显示我想要在折叠中实现的文本区域,这样当我点击该复选框时我想看到内容。单击复选框时不显示内容

import React from 'react';
import { Grid, FormControlLabel, Checkbox} from '@mui/material';
import { Collapse } from 'react-collapse';
import { Formik } from 'formik';
import { useFormik } from 'formik';
import MyTextField from './MyTextField';
let defaultInitialIngestObject = {
  pushEnabled: true
}
export default function App(props) {
  const { initialValues } = props
  const formik = useFormik({
    initialValues: Boolean(initialValues) ? initialValues : defaultInitialIngestObject,

  });
  return (
    <div>

      <Grid item xs={12}>
      
          <Grid item xs={4}>
            <FormControlLabel
              style={{ margin: 0, padding: 0, marginTop: '8px', verticalAlign: 'top' }}
              label="Submit"
              id="sub"
              control={

                < Checkbox size="large"
                  onClick={(evt) => formik.setFieldValue("sub", evt.target.checked)}
                  checked={formik.values['sub']}
                />
              }
            />
          </Grid>

          <Collapse in={formik.values.sub}>
            <Grid item xs={4}>

              <MyTextField
                disabled={formik.values.sub}
                id="firs"
                label="First"
                formik={formik}
              />
            </Grid>
          </Collapse>

        </Grid>
  
    </div>
  )
}

【问题讨论】:

    标签: reactjs formik


    【解决方案1】:

    有几件事需要调整。
    首先,您试图将不受控制的输入更改为受控 在控制台中导致此警告 Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component.

    让我们解决这些问题。

    • 发生警告的原因是您正在使用未定义的值安装输入,然后稍后当您单击它时,您将设置一个值为 true [checked]。
      这将导致上述错误,因此让我们将值预定义为 假 [未检查]

         checked={formik.values.sub || false}
      
    • 其次,根据 MUI Checkbox 文档,正确的 API 不是 onClick 而是 onChange https://mui.com/material-ui/api/form-control-label/ ,所以,让我们更新一下

         onChange={
            (evt) => formik.setFieldValue("sub", evt.target.checked)
         }
      
    • 第三,根据库文档,属性 in 似乎不在 API 中。 https://www.npmjs.com/package/react-collapse
      我将其更改为isOpened,现在可以使用了。

         <Collapse 
          // in={formik.values.sub}
          isOpened={formik.values.sub}
         >
      

    我在这里创建了一个带有工作版本的沙箱。
    https://codesandbox.io/s/stackoverflow-example-checkbox-expand-8o2wzk?file=/src/App.js

    附言。对于您的下一个问题,请提供一个沙箱,以便其他人更容易提供帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-17
      • 2013-12-15
      • 1970-01-01
      • 1970-01-01
      • 2021-04-09
      相关资源
      最近更新 更多