在React中管理对话框的最佳方法

问题描述 投票:0回答:2

我想知道是否没有更好的方法来管理功能组件中对话框的打开和关闭?您可以在下面找到一个示例:

import React, { useState } from 'react';
import PropTypes from 'prop-types';

import EditDialog from './EditDialog';
import DeleteDialog from './DeleteDialog';


const ContactCard = ({ contact }) => {
  const [editOpen, setEditOpen] = useState(false);
  const [deleteOpen, setDeleteOpen] = useState(false);

  const handleEditOpen = () => {
    setEditOpen(true);
  };
  const handleEditClose = () => {
    setEditOpen(false);
  };
  const handleDeleteOpen = () => {
    setDeleteOpen(true);
  };
  const handleDeleteClose = () => {
    setDeleteOpen(false);
  };

  const { type, firstName, lastName, phoneNumber, mail } = contact;
  return (
    <>
      <div className={classes.main}>
        {/* All my contact informations */}
      </div>
      <EditDialog handleClose={handleEditClose} open={editOpen} />
      <DeleteDialog handleClose={handleDeleteClose} open={deleteOpen} />
    </>
  );
};

ContactCard.propTypes = {
  contact: PropTypes.object.isRequired
};

export default ContactCard;

我认为这是超级多余的,但是我找不到更好的方法来管理几个不同的对话框。

const handleEditOpen = () => {
    setEditOpen(true);
  };
  const handleEditClose = () => {
    setEditOpen(false);
  };
  const handleDeleteOpen = () => {
    setDeleteOpen(true);
  };
  const handleDeleteClose = () => {
    setDeleteOpen(false);
  };

非常感谢您的时间和建议!

reactjs modal-dialog material-ui react-hooks
2个回答
0
投票
import React, {useState} from "react"; import ReactDOM from "react-dom"; function App() { const [editCard, setEditCard] = useState(false) return ( <div className="App"> <h1>Hello CodeSandbox</h1> <h2>Start editing to see some magic happen!</h2> <button onClick={() => setEditCard(!editCard)}>Toggle Edit</button> {editCard && <div>Card is open for editing</div>} </div> ); } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement);

这里是您的代码的另一个示例。我没有运行它,但是它应该看起来像这样。

import React, { useState } from 'react';
import PropTypes from 'prop-types';
import EditDialog from './EditDialog';
import DeleteDialog from './DeleteDialog';


const ContactCard = ({ contact }) => {
  const [editOpen, setEditOpen] = useState(false);
  const [deleteOpen, setDeleteOpen] = useState(false);

  const handleEdit = () => {
    setEditOpen(!editOpen);
  };

  const handleDelete = () => {
    setDeleteOpen(!deleteOpen);
  };

  const { type, firstName, lastName, phoneNumber, mail } = contact;
  return (
    <>
      <div className={classes.main}>
        {/* All my contact informations */}
      </div>
      {
         editOpen && <EditDialog handleEdit={handleEdit} />
      }
      {
        deleteOpen && <DeleteDialog handleClose={handleClose} /> 
      }
    </>
  );
};

ContactCard.propTypes = {
  contact: PropTypes.object.isRequired
};

export default ContactCard;
© www.soinside.com 2019 - 2024. All rights reserved.