今天我想隐藏 typescript 函数中的 bootstrap5
"bootstrap": "v5.3.1"
madal,我只是获取模态元素并调用隐藏函数,但它似乎不起作用。模式没有按预期隐藏,这是最小的重现代码:
import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import * as bootstrap from 'bootstrap';
const App: React.FC = () => {
const handleModal = (show: boolean, modalId: string) => {
let modal = document.getElementById(modalId);
if (modal) {
var myModal = new bootstrap.Modal(modal);
show ? myModal.show() : myModal.hide();
myModal.hide();
}
}
return (
<div>
<button onClick={() => { handleModal(true, "deleteFileModal") }}>show</button>
<div>
<div className="modal fade" id="deleteFileModal" aria-labelledby="deleteModalLabel" aria-hidden="true">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title" id="deleteModalLabel">Title</h5>
<button type="button" className="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div className="modal-body">
...
</div>
<div className="modal-footer">
<button type="button" className="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" className="btn btn-primary" >Confirm</button>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
export default App;
最后我只是调用模态隐藏,模态最终没有隐藏。我错过了什么吗?我应该怎么做才能解决这个问题?
这里的问题是,当 show 参数为 true 时,您在显示模式后立即调用 myModal.hide() 。这将在显示模式后立即有效地隐藏模式,这可能不是预期的行为。
要解决此问题,您应该删除 myModal.hide(); 行;从函数。您更新后的handleModal函数应如下所示:
const handleModal = (show: boolean, modalId: string) => {
let modal = document.getElementById(modalId);
if (modal) {
var myModal = new bootstrap.Modal(modal);
if (show) {
myModal.show();
} else {
myModal.hide();
}
}
}