步进器。填写表格,必填字段

Stepper. Fill up form, Required fields

我有一个问题。我创建了一个包含 3 个步骤的步进器。我在下面附上了第二步 (2) 表单字段。问题是我的表单中有一些必填字段。即使我没有填满它们,通过单击“下一步”按钮,我也可以转到第 3 步。我希望它向我显示一个警报或 smth,当我不这样做时,它不会让我转到下一步 (3)填写必填字段。我希望描述清楚。感谢您的任何建议!:)

import React, { useState, useEffect } from "react";
import { Button } from "../../components/Button";
import { Checkbox } from "../../components/Checkbox";
import { FormBuilder } from "../../components/FormBuilder";
import { Grid, GridCell, GridRow } from "../../components/Grid";
import { LinearProgress } from "../../components/LinearProgress";
import { Select } from "../../components/Select";
import { TextField } from "../../components/TextField";
import { DynamicForm } from "../../models/DynamicForm";
import "./index.css";
import { Organization } from "../../models/Organization";
import { request } from "../../api";
import { serialize } from "class-transformer";
import { useHistory } from "react-router-dom";
import { Cell } from "../../models/Employee";
import { Ticket } from "../../models/Ticket";

const NUMBER_OF_STEPS = 3;
const screen = {
  first: 1,
  second: 2,
  third: 3,
};

const FormDetails = ({
  dynamicForm,
  organizationId,
}: {
  dynamicForm: DynamicForm;
  organizationId: number;
}) => {
  console.log(organizationId);

  const [isShowOrganiztionFields, setShowOrganizationFields] = useState(null);
  //const [extraApprove, setExtraApprove] = useState(false);
  return (
    <div>
      <h4 style={{ margin: 16 }}>Данные формы</h4>
      <Grid>
        <GridRow>
          <GridCell span={4}>
            <TextField
              required
              label="REQUIRED"
              defaultValue={dynamicForm.name?.value}
              onChange={(value) => (dynamicForm.name.ru = value)}
            />
          </GridCell>
        </GridRow>
        <GridRow>
          <GridCell span={4}>
            <TextField
              required
              maxLength={512}
              textarea
              label="REQUIRED"
              onChange={(value) => (dynamicForm.description.kk = value)}
              defaultValue={dynamicForm.description?.ru}
            />
          </GridCell>
        </GridRow>
        <GridRow>
          <GridCell span={2}>
            <Checkbox
              label="cb2"
              onChange={(value) => (dynamicForm.needExtraApprove = value)}
              defaultChecked={dynamicForm.needExtraApprove}
            />
          </GridCell>
          <GridCell span={2}>
            <TextField
              required
              label="REQUIRED"
              type="number"
              min={1}
              defaultValue={dynamicForm.executionDays?.toString()}
              onChange={(value) =>
                (dynamicForm.executionDays = parseInt(value))
              }
            />
          </GridCell>
          <GridRow>
            <GridCell span={5}>
              <Checkbox
                label="cb5"
                onChange={(value) =>
                  setShowOrganizationFields(
                    (dynamicForm.needExtraApprove = value)
                  )
                }
                defaultChecked={dynamicForm.needExtraApprove}
              />
            </GridCell>
          </GridRow>
          {isShowOrganiztionFields && (
            <GridRow>
              <GridCell span={4}>
                <Select<Organization>
                  required
                  label="REQUIRED"
                  type={Organization}
                  api="/organization"
                  onChange={(organization: Organization) =>
                    setShowOrganizationFields(organization.id)
                  }
                />
              </GridCell>
              <GridCell span={4}>
                <Select<Cell>
                  required
                  defaultValue={dynamicForm.department}
                  label="REQUIRED"
                  type={Cell}
                  api="/state_schedule/cells-list/"
                  params={`code=DEPARTMENT&code=INDEPENDENT_POSITION&organization_id=${organizationId}`}
                  onChange={(value: Cell) =>
                    (dynamicForm.departmentHash = value.positionHash)
                  }
                />
              </GridCell>
            </GridRow>
          )}
        </GridRow>
      </Grid>
    </div>
  );
};

const FormFields = ({ dynamicForm }: { dynamicForm: DynamicForm }) => (
  <div>
    <h4 style={{ margin: 16 }}>Поля формы</h4>
    <FormBuilder dynamicForm={dynamicForm} />
  </div>
);

export default () => {
  const [step, setStep] = useState(1);
  const [dynamicForm, setDynamicForm] = useState<DynamicForm>(
    new DynamicForm()
  );
  const [organizationId, setorganizationId] = useState(null);

  let progress = parseFloat(((step - 1) * (1 / NUMBER_OF_STEPS)).toFixed(2));
  const onBackButtonPress = () => {
    if (step > 0) {
      setStep((prev) => prev - 1);
    }
  };

  const onNextButtonPress = () => {
    event.preventDefault();
    if (step < screen.third) {
      setStep((prev) => prev + 1);
    } else {
      console.log("submit!");
      //submit
    }
  };

  let content = (
    <SubDivision
      dynamicForm={dynamicForm}
      onOrganization={(id) => setorganizationId(id)}
    />
  );
  if (step === screen.second) {
    content = (
      <FormDetails dynamicForm={dynamicForm} organizationId={organizationId} />
    );
  } else if (step === screen.third) {
    content = <FormFields dynamicForm={dynamicForm} />;
  }
  const history = useHistory();
  const onSubmitTest = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    try {
      await request("/service-desk/forms/", {
        method: "POST",
        body: serialize(dynamicForm),
      });

      history.push({
        pathname: "/service-desk/application-form",
      });
    } catch (error) {
      console.log(error);
      alert("error");
    }
  };

  return (
    <form onSubmit={onSubmitTest} noValidate={step === screen.third}>
      <LinearProgress progress={progress} determinate />
      {content}
      <div className="request-btn-container">
        <Button
          label="back"
          disabled={step == 1}
          onClick={onBackButtonPress}
        />
        {step === 3 ? (
          <Button label="save" raised type="submit" />
        ) : (
          <Button
            label="next"
            disabled={step == 3}
            onClick={onNextButtonPress}
          />
        )}
      </div>
    </form>
  );
};

如果未输入必填字段,您可以添加一些条件检查以禁用按钮,例如:

<Button
  label="next"
  disabled={step == 3 || (dynamicForm.name?.value === undefined)}
  onClick={onNextButtonPress}
/>