Поле в модальном диалоговом окне становится неинтерактивным после удаления записейJavascript

Форум по Javascript
Ответить Пред. темаСлед. тема
Anonymous
 Поле в модальном диалоговом окне становится неинтерактивным после удаления записей

Сообщение Anonymous »

У меня есть настольное веб -приложение, которое я строю с помощью Electron и React.js. < /p>
Проблема заключается в следующем: < /p>

При создании и обновлении записей все работает нормально; Это достигается с помощью модального диалога. Это означает, что я не могу их сосредоточить и не могу ввести текстовые поля. class = "lang-ts prettyprint-override">import React, { useState } from 'react';
import {
Box, Typography, Paper, Button, TextField, IconButton,
Table, TableBody, TableCell, TableContainer, TableHead, TableRow,
Dialog, DialogActions, DialogContent, DialogTitle,
Snackbar, Alert
} from '@mui/material';
import DeleteIcon from '@mui/icons-material/Delete';
import EditIcon from '@mui/icons-material/Edit';
import { useData } from '../context/DataContext';

const DepartmentsAreas = () => {
const { departments, areas, addDepartment, addArea, updateDepartment, updateArea, deleteDepartment, deleteArea } = useData();

// Estado para el diálogo de departamentos
const [openDeptDialog, setOpenDeptDialog] = useState(false);
const [deptName, setDeptName] = useState('');
const [deptDescription, setDeptDescription] = useState('');
const [editingDeptId, setEditingDeptId] = useState(null);

// Estado para el diálogo de áreas
const [openAreaDialog, setOpenAreaDialog] = useState(false);
const [areaName, setAreaName] = useState('');
const [areaDescription, setAreaDescription] = useState('');
const [areaDepartmentId, setAreaDepartmentId] = useState('');
const [editingAreaId, setEditingAreaId] = useState(null);

// Estado para notificaciones
const [notification, setNotification] = useState({
open: false,
message: '',
severity: 'info'
});

// Funciones para mostrar/ocultar notificaciones
const showNotification = (message, severity = 'info') => {
setNotification({
open: true,
message,
severity
});
};

const handleCloseNotification = () => {
setNotification({
...notification,
open: false
});
};

// Manejadores para departamentos
const handleOpenNewDeptDialog = () => {
setDeptName('');
setDeptDescription('');
setEditingDeptId(null);
setOpenDeptDialog(true);
};

const handleOpenEditDeptDialog = (dept) => {
setDeptName(dept.name);
setDeptDescription(dept.description);
setEditingDeptId(dept.id);
setOpenDeptDialog(true);
};

const handleCloseDeptDialog = () => {
setOpenDeptDialog(false);
};

const handleSaveDepartment = async () => {
if (!deptName.trim()) {
showNotification('Por favor ingrese un nombre para el departamento', 'error');
return;
}

// Cerrar el diálogo primero
setOpenDeptDialog(false);

try {
if (editingDeptId) {
// Editar departamento existente
await updateDepartment({
id: editingDeptId,
name: deptName,
description: deptDescription
});
showNotification('Departamento actualizado correctamente', 'success');
} else {
// Crear nuevo departamento
await addDepartment({
name: deptName,
description: deptDescription
});
showNotification('Departamento creado correctamente', 'success');
}
} catch (error) {
console.error('Error al guardar departamento:', error);
showNotification('Error al guardar el departamento', 'error');
}
};

const handleDeleteDepartment = async (id) => {
if (window.confirm('¿Está seguro de eliminar este departamento? También se eliminarán todas las áreas asociadas.')) {
try {
// Eliminamos el departamento
await deleteDepartment(id);
// Luego mostramos la notificación
showNotification('Departamento eliminado correctamente', 'success');
} catch (error) {
console.error('Error al eliminar departamento:', error);
showNotification('Error al eliminar el departamento', 'error');
}
}
};

// Manejadores para áreas
const handleOpenNewAreaDialog = () => {
setAreaName('');
setAreaDescription('');
setAreaDepartmentId('');
setEditingAreaId(null);
setOpenAreaDialog(true);
};

const handleOpenEditAreaDialog = (area) => {
setAreaName(area.name);
setAreaDescription(area.description);
setAreaDepartmentId(area.departmentId);
setEditingAreaId(area.id);
setOpenAreaDialog(true);
};

const handleCloseAreaDialog = () => {
setOpenAreaDialog(false);
};

const handleSaveArea = async () => {
if (!areaName.trim()) {
showNotification('Por favor ingrese un nombre para el área', 'error');
return;
}

if (!areaDepartmentId) {
showNotification('Por favor seleccione un departamento', 'error');
return;
}

// Cerrar el diálogo primero
setOpenAreaDialog(false);

try {
if (editingAreaId) {
// Editar área existente
await updateArea({
id: editingAreaId,
name: areaName,
description: areaDescription,
departmentId: areaDepartmentId
});
showNotification('Área actualizada correctamente', 'success');
} else {
// Crear nueva área
await addArea({
name: areaName,
description: areaDescription,
departmentId: areaDepartmentId
});
showNotification('Área creada correctamente', 'success');
}
} catch (error) {
console.error('Error al guardar área:', error);
showNotification('Error al guardar el área', 'error');
}
};

const handleDeleteArea = async (id) => {
if (window.confirm('¿Está seguro de eliminar esta área?')) {
try {
// Eliminamos el área
await deleteArea(id);
// Luego mostramos la notificación
showNotification('Área eliminada correctamente', 'success');
} catch (error) {
console.error('Error al eliminar área:', error);
showNotification('Error al eliminar el área', 'error');
}
}
};

return (


Gestión de Departamentos y Áreas


{/* Sección de Departamentos */}


Departamentos

Nuevo Departamento







Nombre
Descripción
Acciones



{departments.map((dept) => (

{dept.name}
{dept.description}

handleOpenEditDeptDialog(dept)}>


handleDeleteDepartment(dept.id)}>




))}
{departments.length === 0 && (


No hay departamentos registrados


)}





{/* Sección de Áreas */}


Áreas

Nueva Área







Nombre
Descripción
Departamento
Acciones



{areas.map((area) => {
const department = departments.find(d => d.id === area.departmentId);
return (

{area.name}
{area.description}
{department ? department.name : 'N/A'}

handleOpenEditAreaDialog(area)}>


handleDeleteArea(area.id)}>




);
})}
{areas.length === 0 && (


No hay áreas registradas


)}





{/* Diálogo para Departamentos */}
{openDeptDialog && (

{editingDeptId ? 'Editar Departamento' : 'Nuevo Departamento'}


setDeptName(e.target.value)}
required
error={!deptName}
helperText={!deptName ? 'Este campo es requerido' : ''}
sx={{ mb: 2 }}
autoFocus={false}
InputProps={{
readOnly: false,
}}
/>
setDeptDescription(e.target.value)}
multiline
rows={3}
InputProps={{
readOnly: false,
}}
/>



Cancelar

Guardar



)}

{/* Diálogo para Áreas */}
{openAreaDialog && (

{editingAreaId ? 'Editar Área' : 'Nueva Área'}


setAreaName(e.target.value)}
required
error={!areaName}
helperText={!areaName ? 'Este campo es requerido' : ''}
sx={{ mb: 2 }}
autoFocus={false}
InputProps={{
readOnly: false,
}}
/>
setAreaDescription(e.target.value)}
multiline
rows={3}
sx={{ mb: 2 }}
InputProps={{
readOnly: false,
}}
/>
setAreaDepartmentId(e.target.value)}
required
error={!areaDepartmentId}
helperText={!areaDepartmentId ? 'Este campo es requerido' : ''}
SelectProps={{
native: true,
}}
InputProps={{
readOnly: false,
}}
>
Seleccione un departamento
{departments.map((dept) => (

{dept.name}

))}




Cancelar

Guardar



)}

{/* Notificaciones */}


{notification.message}



);
};

export default DepartmentsAreas;



Подробнее здесь: https://stackoverflow.com/questions/796 ... te-records
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Google Maps AutoComplete Результат в модальном диалоговом окне Bootstrap
    Anonymous » » в форуме Html
    0 Ответы
    21 Просмотры
    Последнее сообщение Anonymous
  • Google Maps AutoComplete Результат в модальном диалоговом окне Bootstrap
    Anonymous » » в форуме CSS
    0 Ответы
    15 Просмотры
    Последнее сообщение Anonymous
  • Заблокирован Kendo UI Dropdowntree Filter на модальном диалоговом окне jQuery UI
    Anonymous » » в форуме Jquery
    0 Ответы
    18 Просмотры
    Последнее сообщение Anonymous
  • Заблокирован Kendo UI Dropdowntree Filter на модальном диалоговом окне jQuery UI
    Anonymous » » в форуме Jquery
    0 Ответы
    24 Просмотры
    Последнее сообщение Anonymous
  • Jetpack Compose: клавиатура закрывает текстовое поле в диалоговом окне
    Anonymous » » в форуме Android
    0 Ответы
    104 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Javascript»