未捕获的类型错误:在 React 中使用 Bootstrap 5 模式时无法读取未定义的属性(读取“背景”)
2022-12-24
27284
尝试使用 javascript 显示 bootstrap 5 模式时出错。
const handleClick = (e) => {
e.preventDefault();
const modalElement = document.getElementById('editUserModal');
const modal = Modal.getOrCreateInstance(modalElement);
modal.show();
};
这是模式的代码
const EditModal = () => {
return (
<>
<div
className="modal fade "
id="editUserModal"
aria-hidden="true"
tabIndex="-1"
>
<div className="modal-dialog modal-dialog-centered">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title" id="exampleModalToggleLabel">
Modal 1
</h5>
<button
type="button"
className="btn-close"
data-bs-dismiss="modal"
aria-label="Close"
></button>
</div>
<div className="modal-body">
Show a second modal and hide this one with the button below.
</div>
<div className="modal-footer">
<button
className="btn btn-primary"
data-bs-target="#exampleModalToggle2"
data-bs-toggle="modal"
data-bs-dismiss="modal"
>
Open second modal
</button>
</div>
</div>
</div>
</div>
</>
);
};
export default EditModal;
Uncaught TypeError: Cannot read properties of undefined (reading 'backdrop')
at Modal._initializeBackDrop (modal.js:158:39)
at new Modal (modal.js:69:27)
at Modal.getOrCreateInstance (base-component.js:65:41)
at HTMLAnchorElement.<anonymous> (modal.js:364:22)
at HTMLDocument.handler (event-handler.js:118:19)
我不想依赖 react-bootstrap 库。针对同一问题还有另一个类似的问题,但也没有修复方法。
编辑:我正在附加包含 EditModal 的父组件
import ProfileCard from '../../components/profileCard/ProfileCard';
import EditModal from '../../components/editModal/EditModal';
import { Modal } from 'bootstrap';
const Home = () => {
const handleClick = (e) => {
e.preventDefault();
const modalElement = document.getElementById('editUserModal');
const modal = Modal.getOrCreateInstance(modalElement);
modal.show();
};
return (
<>
<a
className="btn btn-primary"
data-bs-toggle="modal"
onClick={handleClick}
role="button"
>
Open first modal
</a>
<div className="container">
<div className="row mt-5">
<div className="col-md-3"></div>
</div>
</div>
<EditModal />
</>
);
};
export default Home;
3个回答
由于您通过点击处理程序显示/隐藏模态框,请尝试删除
data-bs-toggle="modal"
。
Abdu4
2023-08-14
在代码的这一部分
<a
className="btn btn-primary"
data-bs-toggle="modal"
onClick={handleClick}
role="button"
>
您添加了
data-bs-toggle
并且您在
handleClick
const modal = Modal.getOrCreateInstance(modalElement);
modal.show();
中也有这个
这两者无法一起工作
如果您从“a”标签中删除
data-bs-toggle="modal"
,则问题将得到解决。
因为您的
handleClick
函数中已经有模态操作
alireza alizade
2023-12-20
请尝试以下操作来明确设置背景:
const handleClick = (e) => {
e.preventDefault();
const modalElement = document.getElementById('editUserModal');
const modal = new Modal(modalElement, {backdrop: false, keyboard: true, focus: true});
modal.show();
};
Link477
2023-10-28