javascript - 单击删除按钮时如何打开模态框?

标签 javascript reactjs

当用户单击删除客户端的按钮时,我正在尝试打开一个模式(其中显示您确定要删除客户端)。 为了打开模式,我创建了一个 openModal 函数,但不确定如何在此代码中调用此函数。

ClientList.js

export default function ListClients() {
 const [showModal, setShowModal] = useState();
 const [userlist, setUserlist] = useState([]);
 const [selectedID,setSelectedID]=useState('');

   function deleteClient() {
   if(selectedID){
       const userParams = {
          clientName:
        clientName,
          country: country,
          clientid: selectedID,
        };
        
       axios
          .delete(process.env + "client", {
        data: clientParams,
          })
          .then((response) => {
        setClientlist(clientlist.filter((client) => client.id !== clientId));
          })
          .catch((error) => {
        console.log(error);
          });
   }



  }

return(
     <div>
    <tbody>
        {userlist.length > 0 ? (
           userlist.map((userlist) => (
             <tr key={userlist.id}>
                <td>
                  <div">
                      {userlist.id}
                   </div>
                </td>
                <td>
                  <button type="button" onClick={() => setSelectedID(userlist.id)}> 
                      Delete
                  </button>
                 </td
             </tr>
        </tbody>

         //the idea is to pass the  state for modal to show 
       <ModalDelete showModal={showModal} setShowModal={setShowModal} onCancel={()=>setSelectedID('')} onDel={deleteClient}/>
      </div>
);

ModalDelete.js

export default function ModalDelete({ showModal, setShowModal,onCancel,onDel }) {
 
return(
  <div>
    { showModal ? <Transition.Root show={showModal}>  
       <div>
       <p> Are you sure you want to delete the client?</p>
    </div>

    <div>
        <button type="button" onClick={onDel}>Yes</button>
            <button type="button" onClick={() => {
            setShowModal(false);
            onCancel();
            }} >
              Go Back
            </button>
          </div>
    </Transition.Root> : null }
  </div>
);
}

如何调用此代码中的函数,以在单击删除的按钮时打开模式?

最佳答案

您只需在删除按钮上执行此操作即可(您不需要 openModal):

 <button
  type="button" 
  onClick={() => {
    setSelectedID(userlist.id);
    setShowModal(true);
   }}
 >
  Delete
 </button>

关于javascript - 单击删除按钮时如何打开模态框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71208361/

相关文章:

XSL 文档中的 JavaScript For 循环

javascript - 单击按钮时的 Angularjs 过滤器

javascript - 如何分离axios获取数组对象

javascript - 我如何将我的js代码迁移到reactjs并调用它?

reactjs - 使用 react-redux-firebase 的 Firebase Firestore 查询

Javascript 执行失败

javascript - D3.js 将整数轴更改为字符串

javascript - 如何恢复另一个组件的值?

javascript - React + JS 文件,使用 Atom + Chrome 控制台未捕获错误 : Minified exception,

javascript - 使用 eval()...