#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 amp;amp; 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;
я пытаюсь создать многоразовый компонент автозаполнения пользовательского интерфейса материала, чтобы использовать его в форме. Но я не могу использовать обработчик onchange в компоненте автозаполнения. я не могу отобразить значение компонента автозаполнения в состоянии formdata. Клиент в formdata имеет значение идентификатора, сгенерированного mongodb, и при публикации данных формы я хочу использовать идентификатор клиента в качестве значения. но при выборе значения в автозаполнении я хочу использовать его в качестве имени
Комментарии:
1. Пожалуйста, добавьте цвет кода и кодовое поле, если можете