Передача данных в диалоговое окно при нажатии

#reactjs #forms #material-ui

#reactjs #формы #материал-пользовательский интерфейс

Вопрос:

Я бы хотел, чтобы при нажатии на мой аккордеон данные в этой строке переходили в форму моего диалогового окна. Но я не получаю никаких данных в форме.

Почему форма не получает данные?

 import React, { useEffect, useState } from 'react';
import clsx from 'clsx';
import PropTypes from 'prop-types';
import moment from 'moment';
import PerfectScrollbar from 'react-perfect-scrollbar';
import {
  Avatar,
  Box,
  Card,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Grid,
  SvgIcon,
  InputAdornment,
  CardContent,
  TextField,
  ListItemText,
  ListItem,
  List,
  Checkbox,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TablePagination,
  IconButton,
  Typography,
  makeStyles,
  Button
} from '@material-ui/core';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import getInitials from 'src/utils/getInitials';
import EditProjAdminE from './editProjAdminE';
import AjoutEven from './ajoutEven';
import dataEven from './data';
import SpeedDialTooltipOpen from './speedDialE';
import EditIcon from '@material-ui/icons/Edit';
import AddIcon from '@material-ui/icons/Add';
import { Search as SearchIcon } from 'react-feather';
import { Slide } from 'react-slideshow-image';
import axios from "axios";
import DeleteIcon from '@material-ui/icons/Delete';



const useStyles = makeStyles((theme) => ({
  root: {},
  absolute: {
    position: 'absolute',
    bottom: theme.spacing(2),
    right: theme.spacing(3),
  },
  avatar: {
    marginRight: theme.spacing(2)
  }
}));

const ProjetAdminE = ({ className, dataEleve, ...rest }) => {
  const classes = useStyles();


  // const [data, setData] = useState(dataEven);
  const [filteredEven, setFilteredEven] = useState([]);
  const [dataSearch, setDataSearch] = useState([]);
  const [loading, setLoading] = useState(false);
  const [limit, setLimit] = useState(10);
  const [page, setPage] = useState(0);

  const [selectedeleveIds, setSelectedeleveIds] = useState([]);

  // const dateR = new Date()
  // const dateReel = dateR.setDate(dateR.getDate() 1);

  const handleLimitChange = (event) => {
    setLimit(event.target.value);
  };

  const handlePageChange = (event, newPage) => {
    setPage(newPage);
  };

  const [search, setSearch] = useState('');

  useEffect(() => {
    setLoading(true);
    axios
      .get("http://localhost:8080/employees")
      .then((res) => {
        setDataSearch(res.data);
        setLoading(false);
      })
      .catch((err) => {
        console.log(err);
      });
  }, []);


  const suppression = (id) => {

    fetch('http://localhost:8080/evenement/'   id, {
      method: 'DELETE',
    })
      .then(res => res.text())
      .then(res => {
        // setDataSearch(res.data);
        console.log(res)
      })

    alert(JSON.stringify("événement Numéro "   id   " supprimé"))

  }

  // const modification =(id) =>{

  //   fetch('http://localhost:8080/update/'   id, {
  //     method: 'PUT',
  //   })
  //   .then(res => res.text()) 
  //   .then(res => console.log(res))

  //   alert(JSON.stringify("événement Numéro "  id  " modifié"))

  // }

  // alert(JSON.stringify(index))

  useEffect(() => {
    setFilteredEven(
      dataSearch.filter((Evenen) =>
        Evenen.descrip_evene.toLowerCase().includes(search.toLowerCase())
      )
    );
  }, [search, dataSearch]);


  return (
    <Card
      className={clsx(classes.root, className)}
      {...rest}
    >

      <>
        <Box
          display="flex"
          justifyContent="left"
          style={{ height: 30 }}
        >
          <Typography variant="h3" style={{ margin: 10, color: '#1565C0' }}>
            LISTE DES EVENEMENTS
            </Typography>
        </Box>

        <Box mt={3}>
          <Card>
            <CardContent>
              <Box maxWidth={500}>
                <TextField
                  value={search}
                  onChange={e => {
                    setSearch(e.target.value);
                  }}
                  fullWidth
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <SvgIcon
                          fontSize="small"
                          color="action"
                        >
                          <SearchIcon />
                        </SvgIcon>
                      </InputAdornment>
                    )
                  }}
                  placeholder="Recherchez un évenement"
                  variant="outlined"
                />
              </Box>
              {/* <Button
                  color="primary"
                  variant="contained"
                  onClick = {alert(JSON.stringify(dateReel))}
                >
                  Rechercher
              </Button> */}

            </CardContent>
          </Card>
        </Box>


        <Grid>
          <Grid spacing={1} md={8} xs={12} style={{ margin: 2 }}>
            {filteredEven.map((recherche, index) => (

              <Accordion style={{ marginTop: 30 }} >
                <AccordionSummary
                  expandIcon={<ExpandMoreIcon />}
                  aria-controls="panel1a-content"
                  id="panel1a-header"
                  style={{ backgroundColor: '#DADFD9' }}
                >
                  <Grid container spacing={1} md={12} xs={12} style={{ margin: 0 }}>
                    <Grid item md={2} xs={4}>
                      {recherche.date_even.slice(0, 10)}
                    </Grid>

                    <Grid item md={2} xs={2}>
                      {recherche.prix_even}
                    </Grid>
                    <Grid item md={2} xs={3}>
                      {recherche.statut}
                    </Grid>
                    <Grid item md={3} xs={3}>
                      {recherche.descrip_evene}
                    </Grid>
                    <Grid item md={3} xs={8} style={{ marginTop: -10 }}>
                      <IconButton>
                        <EditProjAdminE
                          dataSearch={dataSearch}
                          setDataSearch={setDataSearch}
                          id={recherche.id}
                        />
                      </IconButton>
                      <IconButton
                        onClick={async () => {
                          suppression(recherche.id)
                          window.location.reload(false)
                        }}
                      >
                        <DeleteIcon fontSize="small" style={{ color: 'black' }} />
                      </IconButton>
                      {/* <SpeedDialTooltipOpen/> */}
                    </Grid>
                  </Grid>
                </AccordionSummary>
                <AccordionDetails>

                  <List>

                    <ListItem>
                      <ListItemText primary={
                        <Typography variant="caption" style={{ fontWeight: 'bold', fontSize: 16 }}>
                          {recherche.id}
                        </Typography>
                      }
                        secondary="Membre concerné"
                      />
                    </ListItem>

                    <ListItem>
                      <ListItemText primary={
                        <Typography variant="caption" style={{ fontWeight: 'bold', fontSize: 16 }}>
                          {recherche.lieu}
                        </Typography>

                      }
                        secondary="Lieu"
                      />
                    </ListItem>


                    <ListItem>
                      <ListItemText primary={
                        <Typography variant="caption" style={{ fontWeight: 'bold', fontSize: 16 }}>
                          {recherche.heure}
                        </Typography>
                      }
                        secondary="Heure"
                      />
                    </ListItem>
                  </List>

                </AccordionDetails>
              </Accordion>
            ))}
          </Grid>

        </Grid>

        <AjoutEven />
      </>


    </Card>
  );
};

// Results.propTypes = {
//         className: PropTypes.string,
//   dataEleve: PropTypes.array.isRequired
// };

export default ProjetAdminE; 

editProjetEven.js

 import React, { useState } from 'react';
import clsx from 'clsx';
import PropTypes from 'prop-types';
import moment from 'moment';
import PerfectScrollbar from 'react-perfect-scrollbar';
import { makeStyles, useTheme, withStyles } from '@material-ui/core/styles';
import {
    Button,
    Grid,
    MenuItem,
    DialogContent,
    DialogActions,
    Dialog,
    IconButton,
    Avatar,
    TextField,
    DialogTitle,
} from '@material-ui/core';
import getInitials from 'src/utils/getInitials';
import CreateIcon from '@material-ui/icons/Create';
import EditIcon from '@material-ui/icons/Edit';
import DeleteIcon from '@material-ui/icons/Delete';

const useStyles = makeStyles((theme) => ({
    root: {
        width: 645,
    },
    item: {
        height: 50
    },
    buttonDial: {
        color: "#fff",
    },
    buttonAnnuler: {
        color: "red"
    },
    buttonSave: {
        background: "#558b2f",
        color: "#558b2f",
    }
}));



export default function EditProjAdminE(setDataSearch,dataSearch,data,setData,id,index) {

    const classes = useStyles();

    const [open, setOpen] = React.useState(false);
    const [opens, setOpens] = React.useState(false);

    const handleChange = event => {
        const { name, value } = event.target
        setDataSearch({ ...dataSearch, [name]: value })
    }


    // const fullScreen = useMediaQuery(theme.breakpoints.down(645));

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

    const handleClose = () => {
        setOpen(false);
    };
    // const handleInputChange = event => {
    //     const { name, value } = event.target
    //     setData({ ...data, [name]: value })
    // }

    // const item = dataSearch.find(id);

    return (
        <div>

            <div display="flex">
                <IconButton onClick={handleClickOpen}>
                    <EditIcon fontSize="small" alt="modifier" style={{ color: '#205723' }} />
                </IconButton>
            </div>
            
                <Dialog
                    fullWidth
                    // fullScreen
                    open={open }
                    onClose={handleClose}
                    aria-labelledby="responsive-dialog-title"
                    maxWidth = 'md'
                >
                    {/* { index ==="" ? "aucune information": 
                    <> */}
                    <DialogTitle id="responsive-dialog-title">Virement</DialogTitle>

                    <DialogContent >
                        <Grid container spacing={1}>

                            <Grid item md={4} xs={12}>
                                <TextField
                                    fullWidth
                                    margin="dense"
                                    type="text"
                                    name="prix_even"
                                    value={dataSearch.prix_even}
                                    // defaultValue={dataSearch.prix_even}
                                    label="Prix"
                                    variant="outlined"
                                    onChange={(event) => handleChange(event)}
                                />
                            </Grid>

                            <Grid item md={4} xs={12}>
                                <TextField
                                    fullWidth
                                    margin="dense"
                                    type="text"
                                    name="heure"
                                    value={dataSearch.heure}
                                    label="Heure"
                                    variant="outlined"
                                    onChange={(event) => handleChange(event)}
                                />
                            </Grid>

                            <Grid item md={4} xs={12}>
                                <TextField
                                    fullWidth
                                    margin="dense"
                                    type="text"
                                    name="lieu"
                                    value={dataSearch.lieu}
                                    label="Lieu"
                                    variant="outlined"
                                    onChange={(event) => handleChange(event)}
                                />
                            </Grid>

                            <Grid item md={4} xs={12}>
                                <TextField
                                    fullWidth
                                    margin="dense"
                                    type="date"
                                    name="date_even"
                                    value={dataSearch.date_even}
                                    helperText="Date de l'événement"
                                    variant="outlined"
                                    onChange={(event) => handleChange(event)}
                                />
                            </Grid>

                            <Grid item md={4} xs={12}>
                                <TextField
                                    fullWidth
                                    margin="dense"
                                    type="text"
                                    name="descrip_even"
                                    value={dataSearch.descrip_even}
                                    label="Descr de l'événement"
                                    variant="outlined"
                                    onChange={(event) => handleChange(event)}
                                />
                            </Grid>

                            <Grid item md={4} xs={12}>
                                <TextField
                                    fullWidth
                                    margin="dense"
                                    type="text"
                                    name="statut"
                                    value={dataSearch.statut}
                                    label="Statut"
                                    variant="outlined"
                                    onChange={(event) => handleChange(event)}
                                />
                            </Grid>

                        </Grid>

                    </DialogContent>
                    <DialogActions>
                        <Button
                        // onClick={alert(JSON.stringify(dataSearch))}
                        >
                            Modifier
                    </Button>
                        <Button onClick={handleClose} className={classes.buttonAnnuler}>
                            Fermer
                    </Button>
                    </DialogActions>
                    {/* </>
                    } */}
                </Dialog>


            </div>
    );
} 

Комментарии:

1. Этот сайт предназначен только для вопросов на английском языке — пожалуйста, соблюдайте правила сайта — спасибо

Ответ №1:

по щелчку я передаю индекс объекта в массив и отправляю его в новый созданный мной массив

 <IconButton onClick={async () => {
    setData({ ...dataSearch[index] })
    handleClickOpen()
 }}
 >
    <EditIcon fontSize="small" alt="modifier" style={{ color: '#205723' }} />
</IconButton> 

Комментарии:

1. Если мой ответ не помог, вам не нужно повышать или отмечать его как принятый, но, по крайней мере, в своем ответе укажите только то, что решило проблему (вместо вставки полного кода), чтобы ваш вопрос мог быть полезен другим… Я заметил, что вы сделали, как я предложил, и добавили вызов setData в onClick вызов кнопки, этого было достаточно?

2. Для слишком длинного ответа это первый раз, когда я сделал сообщение. Да. это решило проблему, спасибо

Ответ №2:

handleClickOpen Кажется, что он только открывает диалоговое окно, а не вызывает setDataSearch({ ...dataSearch, [name]: value }) , которое, по-видимому, отвечает за добавление значений к dataSearch объекту, который используется в ваших полях формы.

Я бы лично дважды проверил, получает ли компонент EditProjAdminE правильное dataSearch , а затем позже вызвал аналогичную функцию handleChange при запуске события open.