import c from '../Profile.module.css';
import { useState } from 'react';
import { createPortal } from 'react-dom';
import Modal from '../Modal/Modal';
const TransactionItem = (props) => {
const modalRoot = document.querySelector('#root > div');
const [showModal, setShowModal] = useState(false);
const short = str => str.substring(str.length - 4) + '...' + str.substring(0, 5);
const handleClose = () => {
setShowModal(false);
}
return (
<div className={c.transaction_item} onClick={() => setShowModal(true)}>
<div className={c.transaсtion_data}>
<div className={c.icon}><span>$</span></div>
<div className={c.transaction_info}>
{props.type === "+" ? 'Пополнение' : 'Перевод'}
<div className={c.transaction_where}>{short(props.from)} -> {short(props.to)}</div>
</div>
</div>
<span className={c.transaction_total}>{props.type + props.total}</span>
{showModal && createPortal(
<Modal onClose={handleClose} date='23.05.2024 в 09:41' {...props} />,
modalRoot
)}
</div>
)
}
export default TransactionItem;
由于某种原因我无法关闭模式窗口。 但如果你这样做:
const handleClose = () => {
setTimeout(() => {
setShowModal(false);
}, 0)
}
由于某种原因,模式窗口将关闭 这可能与什么有关?是否有其他选项可以在没有 setTimeout 拐杖的情况下解决问题?
模态包含在其中:
<div className={c.transaction_item} onClick={() => setShowModal(true)}>
大概关闭模式的行为涉及一个单击事件,该事件会冒泡到包含元素并最终到达此事件处理程序。
它与
setTimeout
一起使用的原因是因为这会将对 setShowModal(false)
的调用延迟到事件处理完成之后。 因此,在这种情况下,它会在 setShowModal(true)
之后立即调用,而如果没有 setTimeout
,则顺序会相反。
无论在模式中处理单击事件的位置,请在单击事件上调用
stopPropagation()
。 例如,如果在模态中你有这个:
onClick={onClose}
您可以将其替换为:
onClick={e => {
e.stopPropagation();
onClose();
}}