0

我有一个反应应用程序,父组件有一个按钮,单击该按钮会显示一个简单的对话框,其中包含一个文本输入和一个提交按钮。启用严格模式。有两个问题

  1. 表单输入设置为在输入中显示初始值(initialValues设置了formik)但未设置
  2. 单击按钮时,我在控制台中看到错误;

Warning: findDOMNode is deprecated in StrictMode. findDOMNode was passed an instance of Transition which is inside StrictMode. Instead, add a ref directly to the element you want to reference.

对话框组件来自 Material UI,表单来自 Formik。我在这里创建了一个简单的重现。错误出现在开发工具控制台中。什么会导致该错误,为什么该值未初始化?

这是父组件;

import React, { useState } from "react";
import { Button, Typography } from "@material-ui/core";

import ProfileEditor from "./ProfileEditor";

function ProfileManager() {
  const [open, setOpen] = useState(false);

  const handleClose = () => {
    setOpen(false);
  };

  const handleOpen = () => {
    setOpen(true);
  };

  return (
    <div>
      <Typography variant="h5">Profile Manager</Typography>

      <Button variant="outlined" color="primary" onClick={handleOpen}>
        Open profile editor dialog
      </Button>

      <ProfileEditor open={open} onClose={handleClose}></ProfileEditor>
    </div>
  );
}

export default ProfileManager;

以及上面组件中点击按钮时显示的对话框组件;

import React from "react";
import {
  Button,
  Dialog,
  DialogContent,
  LinearProgress,
  TextField
} from "@material-ui/core";
import { Formik, Form } from "formik";

interface Props {
  open: boolean;
  onClose: () => void;
}

function ProfileEditor(props: Props) {
  return (
    <Dialog open={props.open}>
      <DialogContent>
        <Formik
// initial value not being displayed !!! 
          initialValues={{
            firstName: "Billy"
          }}
          onSubmit={(values, { setSubmitting }) => {
            setTimeout(() => {
              setSubmitting(false);
              alert(JSON.stringify(values, null, 2));
            }, 500);
          }}
        >
          {({ submitForm, isSubmitting }) => (
            <Form>
              <TextField name="firstName" type="text" label="First name" />
              {isSubmitting && <LinearProgress />}
              <br />
              <Button
                variant="contained"
                color="primary"
                disabled={isSubmitting}
                onClick={submitForm}
              >
                Submit
              </Button>
              <Button variant="contained" onClick={props.onClose}>
                Close
              </Button>
            </Form>
          )}
        </Formik>
      </DialogContent>
    </Dialog>
  );
}

export default ProfileEditor;
4

1 回答 1

0

您需要在表单字段中包含一个 value 属性以使其正确初始化。

{({ submitForm, isSubmitting, values }) => (
<Form>
    <TextField
    name="firstName"
    type="text"
    label="First name"
    value={values.firstName} /* you need this prop */
    />

    ...

CodeSandBox:https ://codesandbox.io/s/so-react-formik-inside-material-dialog-sfq4e?file=/ProfileEditor.tsx


关于您在控制台上的问题,我目前不完全确定是什么原因造成的,但如果它困扰您或导致其他问题,也许您可​​以选择退出严格模式

<React.Fragment>
  <ProfileManager></ProfileManager>
</React.Fragment>
于 2020-08-08T06:41:30.570 回答