表单中的自动完成材料 ui

时间:2021-05-10 16:19:54

标签: autocomplete material-ui onchange

import React, { FunctionComponent, useEffect } from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
import CircularProgress from "@material-ui/core/CircularProgress";

interface AsyncProps {
  data: any;
  id: string;
  value: any;
  onChange: ((event: React.ChangeEvent<{}>, value: any, reason: AutocompleteChangeReason, details?: AutocompleteChangeDetails<any> | undefined) => void) | undefined
}

interface DataType {
  name: string;
  _id: string;
}

const Asynchronous: FunctionComponent<AsyncProps> = ({ data, id, value }) => {
  const [open, setOpen] = React.useState(false);
  const [options, setOptions] = React.useState<DataType[]>([]);

  useEffect(() => {
    setOptions(data);
    if (!open) {
      setOptions([]);
    }
  }, [open]);
  const loading = open && data.length === 0;
  return (
    <Autocomplete
      id={id}
      style={{ width: 300 }}
      open={open}
      onChange = {}
      value={value}
      onOpen={() => {
        setOpen(true);
      }}
      onClose={() => {
        setOpen(false);
      }}
      getOptionSelected={(option, value) => {
        return option._id === value._id;
      }}
      getOptionLabel={(option) => {
        return option.name;
      }}
      options={options}
      loading={loading}
      renderInput={(params) => (
        <TextField
          {...params}
          label="Asynchronous"
          variant="outlined"
          InputProps={{
            ...params.InputProps,
            endAdornment: (
              <React.Fragment>
                {loading ? (
                  <CircularProgress color="inherit" size={20} />
                ) : null}
                {params.InputProps.endAdornment}
              </React.Fragment>
            ),
          }}
        />
      )}
    />
  );
};

export default Asynchronous;

  import React, { FunctionComponent, useEffect, useState } from "react";
import {
  Grid,
  TextField,
  makeStyles,
  FormControl,
  InputLabel,
  Theme,
  createStyles,
  Button,
} from "@material-ui/core";
import {
  getTickets,
  deleteTicket,
  updateTicket,
  createTicket,
  getSingleTicket,
} from "../services/ticketDetails";
import { MainTable, TableMouseEventHandler } from "./Table/Table";
import { ITicketDetail } from "../models/ticketDetail";
import DropDown from "./DropDown";
import { getStatus } from "../services/status";
import { IStatus } from "../models/status";
import { getClients } from "../services/client";
import { IPriority } from "../models/priority";
import { getPriority } from "../services/priority";
import FormDialog from "./FormDialog";
import AsynChronous from "./AutoComplete";

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    formControl: {
      margin: theme.spacing(2),
      minWidth: 500,
    },
    button: {
      margin: "8px",
    },
  })
);

const TicketDetails: FunctionComponent = () => {
  const [tickets, SetTickets] = useState<ITicketDetail[]>([]);

  const [formData, setFormData] = useState({
    client: "",
    problemDomain: "",
    subject: "",
    message: "",
    priority: "",
    status: "",
    remarks: "",
  });

  const classes = useStyles();

  const [id, setId] = useState("");
  const [edit, setEdit] = useState(false);
  const [status, setStatus] = useState<IStatus[]>([]);
  const [clients, setClients] = useState([]);
  const [priority, setPriority] = useState<IPriority[]>([]);

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

  useEffect(() => {
    fetchTickets();
    fetchStatus();
    fetchClients();
    fetchPriority();
  }, []);

  const fetchTickets = async () => {
    const tickets = await getTickets();
    SetTickets(tickets);
  };

  const fetchStatus = async () => {
    const data = await getStatus();
    setStatus(data);
  };

  const fetchClients = async () => {
    const data = await getClients();
    setClients(data);
  };

  const fetchPriority = async () => {
    const data = await getPriority();
    setPriority(data);
  };

  const clear = () => {
    setFormData({
      client: "",
      problemDomain: "",
      subject: "",
      message: "",
      priority: "",
      status: "",
      remarks: "",
    });
  };

  const handleSubmit:
    | React.MouseEventHandler<HTMLButtonElement>
    | undefined = async (e) => {
    e.preventDefault();

    try {
      if (edit) {
        await updateTicket(id, { ...formData });
        setEdit(false);
      } else {
        await createTicket(formData);
      }
      setOpen(!open);
      return clear();
    } catch (e) {
      return e;
    }
  };

  const handleEdit: TableMouseEventHandler = async (id) => {
    setId(id);
    setEdit(true);
    const data = await getSingleTicket(id);
    setOpen(!open);
    setFormData({ ...data });
  };

  const handleDelete: TableMouseEventHandler = async (id) => {
    await deleteTicket(id);
  };

  const onChange = (
    event: React.ChangeEvent<{ name?: string; value: unknown }>
  ) => {
    const name = event.target.name as keyof typeof formData;
    setFormData({
      ...formData,
      [name]: event.target.value,
    });
  };

  return (
    <>
      <Grid>
        <FormDialog
          edit={edit}
          handleSubmit={handleSubmit}
          open={open}
          setOpen={setOpen}
          setEdit={setEdit}
          title="TicketDetails Form"
        >
          <form autoComplete="off">
            <FormControl className={classes.formControl}>
              <InputLabel htmlFor="client">Client</InputLabel>
              {/* <DropDown
                value={formData.client}
                data={clients}
                onchange={onChange}
                id="client"
                name="client"
              /> */}
              <AsynChronous
                data={clients}
                id="client"
                value={formData.client}
              />
            </FormControl>

            <FormControl className={classes.formControl}>
              <InputLabel htmlFor="status">Status</InputLabel>
              {/* <DropDown
                value={formData.status}
                data={status}
                onchange={onChange}
                id="status"
                name="status"
              /> */}
              {/* <AsynChronous data={status} id="status" /> */}
            </FormControl>

            <FormControl className={classes.formControl}>
              <InputLabel htmlFor="priority">Priority</InputLabel>
              {/* <DropDown
                value={formData.priority}
                data={priority}
                onchange={onChange}
                id="priority"
                name="priority"
              /> */}
              <AsynChronous
                data={priority}
                id="priority"
                value={formData.priority}
              />
            </FormControl>

            <FormControl className={classes.formControl}>
              <TextField
                label="Problem Domain"
                name="problemDomain"
                value={formData.problemDomain}
                onChange={onChange}
              />
            </FormControl>

            <FormControl className={classes.formControl}>
              <TextField
                label="Subject"
                name="subject"
                value={formData.subject}
                onChange={onChange}
              />
            </FormControl>

            <FormControl className={classes.formControl}>
              <TextField
                label="Message"
                name="message"
                value={formData.message}
                onChange={onChange}
              />
            </FormControl>

            <FormControl className={classes.formControl}>
              <TextField
                label="Remarks"
                name="remarks"
                value={formData.remarks}
                onChange={onChange}
              />
            </FormControl>
          </form>

          {/* <TicketDetailsForm
            edit={edit}
            setEdit={setEdit}
            open={open}
            setOpen={setOpen}
            id={id}
          /> */}
        </FormDialog>

        <Button
          variant="contained"
          color="primary"
          onClick={() => setOpen(true)}
          className={classes.button}
        >
          Add Item
        </Button>

        {tickets.length === 0 ? (
          ""
        ) : (
          <MainTable
            tableHeaders={tickets}
            handleDelete={handleDelete}
            handleEdit={handleEdit}
          />
        )}
      </Grid>
    </>
  );
};

export default TicketDetails;

我正在尝试创建一个可重复使用的材料 ui 自动完成组件以在表单中使用它。但是我无法在自动完成组件中使用 onchange 处理程序。我无法在 formdata 状态中映射自动完成组件的值。 formdata 中的客户端有一个由 mongodb 生成的 id 值,在发布表单数据时,我想使用客户端的 id 作为值。但是在自动完成中选择值时,我想将其用作名称

0 个答案:

没有答案
相关问题