reactjs Formik QRcodeReader按钮自行提交

y1aodyip  于 2022-12-12  发布在  React
关注(0)|答案(1)|浏览(157)

我创建了一个自定义的QR码阅读器,添加为按钮到formik customTextInout.tsx,但当我点击它,它将提交没有值。
在这段代码中,我创建了一个按钮,当你点击它时,它会显示QrCodeReader。

快速阅读器按钮.tsx

import { useState } from "react";
import { QrReader } from "react-qr-reader";
import qrcode from "../assets/qr-code.png";
interface Props {
  setQrData: any;
}

const QrReaderButton: React.FC<Props> = (props) => {
  const [data, setData] = useState<any>();
  const [show, setShow] = useState<boolean>(false);
  let a;
  return (
    <div className="flex flex-col w-max items-center">
      <button
        type="button"
        onClick={() => (!show ? setShow(true) : setShow(false))}
      >
        <img src={qrcode} alt="qr-code" width={40} />
      </button>
      {show && (
        <div className="w-96">
          <QrReader
            onResult={(result: any, error) => {
              if (!!result) {
                setData(JSON.parse(result?.text));
                props.setQrData(JSON.parse(result?.text));
              }
              if (!!error) {
                // console.info(error);
              }
            }}
            constraints={{ facingMode: "user" }}
          />
          <p> {data ? JSON.stringify(data) : "No result"}</p>
        </div>
      )}
    </div>
  );
};

export default QrReaderButton;

在这段代码中,我在formik官方文档CustomTextInput.tsx的帮助下为formik创建了一个自定义输入

import {
  FormControl,
  FormHelperText,
  FormLabel,
  Input,
} from "@chakra-ui/react";
import QrReaderButton from "../QrReaderButton";

const CustomTextInput = ({
  field,
  form: { touched, errors },

  ...props
}: any) => {
  return (
    <FormControl isInvalid={errors.name && touched.name}>
      <FormLabel>{props.label}</FormLabel>
      <div className="flex gap-2">
        <Input {...field} {...props} />
        <div className="w-max">
          <QrReaderButton
            setQrData={() => {
              console.log("test");
            }}
          />
        </div>
      </div>
      <FormHelperText>this is helper</FormHelperText>
    </FormControl>
  );
};

export default CustomTextInput;

在这段代码中,我使用了CustomTextInout组件和chakra-ui模态。

表单模式.tsx

import {
  useDisclosure,
  Button,
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalCloseButton,
  ModalBody,
  FormLabel,
  useToast,
  ModalFooter,
} from "@chakra-ui/react";
import { Formik, Form, Field } from "formik";
import { useNavigate } from "react-router-dom";
import CustomNumberInput from "./CustomInputs/CustomNumberInput";
import CustomOptionInput from "./CustomInputs/CustomOptionInput";
import CustomTextInput from "./CustomInputs/CustomTextInput";
import TokenButton from "./TokenButton";

interface Props {
  key: string;
  Title: string;
  buttonValue?: string;
  image: string;
  nav: string;
  initialValues: any;
  isLoading: boolean;
  apiHook: any;
  validateName: any;
}

const FormModal: React.FC<Props> = (props) => {
  const { isOpen, onOpen, onClose } = useDisclosure();
  const navigate = useNavigate();
  const toast = useToast();
  return (
    <div className="w-full content-center ">
      <TokenButton
        nav={props.nav}
        image={props.image}
        title={props.Title}
        onClick={onOpen}
      />
      <Modal isOpen={isOpen} onClose={onClose}>
        <ModalOverlay />
        <ModalContent>
          <ModalHeader>{props.Title}</ModalHeader>
          <ModalCloseButton />
          <ModalBody>
            <Formik
              initialValues={props.initialValues}
              onSubmit={(values, actions) => {
                setTimeout(() => {
                  alert(JSON.stringify(values, null, 2));
                  actions.setSubmitting(false);
                }, 1000);
                props
                  .apiHook(values)
                  .unwrap()
                  .catch((e: any) => {
                    // alert(JSON.stringify(e, null, 2))
                    toast({
                      status: "error",
                      title: "Error",
                      description: JSON.stringify(e, null, 2),
                      isClosable: true,
                    });

                    if (e.status == 401) {
                      setTimeout(() => {
                        navigate("/login");
                      }, 1000);
                      localStorage.clear();
                    }
                  });
              }}
            >
              {(propsForm) => (
                <Form
                  onSubmit={propsForm.handleSubmit}
                  onReset={propsForm.handleReset}
                  className="w-full h-full bg-[#ced8d7ac] shadow-2xl rounded-2xl p-4 items-center content-center text-current"
                >
                  <FormLabel>{props.Title}</FormLabel>
                  <div className="grid lg:grid-cols-1 md:grid-cols-2 gap-4">
                    {Object.keys(props.initialValues).map((key) => {
                      return (
                        <Field
                          id={key}
                          key={key}
                          name={key}
                          label={key}
                          backgroundColor="#ffffffe1"
                          component={CustomTextInput}
                        />
                      );
                    })}
                  </div>
                  <Button
                    type="submit"
                    isLoading={props.isLoading}
                    className="gre mt-2"
                  >
                    {props.Title}
                  </Button>
                </Form>
              )}
            </Formik>
          </ModalBody>
          <ModalFooter>
            <Button colorScheme="blue" mr={3} onClick={onClose}>
              Close
            </Button>
            <Button variant="ghost">{props.buttonValue}</Button>
          </ModalFooter>
        </ModalContent>
      </Modal>
    </div>
  );
};
export default FormModal;
h9a6wy2h

h9a6wy2h1#

表单中按钮的默认行为是提交。因此,您需要确保指定了提交以外的类型。
参见此处的参考
您的代码如下所示

快速阅读器按钮

import { useState } from "react";
import { QrReader } from "react-qr-reader";
import qrcode from "../assets/qr-code.png";
interface Props {
  setQrData: any;
}

const QrReaderButton: React.FC<Props> = (props) => {
  const [data, setData] = useState<any>();
  const [show, setShow] = useState<boolean>(false);
  let a;
  return (
    <div className="flex flex-col w-max items-center">
      <button
        type="button" //make sure you add this
        onClick={() => (!show ? setShow(true) : setShow(false))}
      >
        <img src={qrcode} alt="qr-code" width={40} />
      </button>
      {show && (
        <div className="w-96">
          <QrReader
            onResult={(result: any, error) => {
              if (!!result) {
                setData(JSON.parse(result?.text));
                props.setQrData(JSON.parse(result?.text));
              }
              if (!!error) {
                // console.info(error);
              }
            }}
            constraints={{ facingMode: "user" }}
          />
          <p> {data ? JSON.stringify(data) : "No result"}</p>
        </div>
      )}
    </div>
  );
};

export default QrReaderButton;

相关问题