我尝试使用 React 构建一个模态,但它不起作用。当我单击打开按钮时,模式不会打开。我尝试搜索这个问题但没有得到任何结果。
我使用
useState
来控制模态框的外观。当它是true
时,它应该显示结果,否则它不应该显示结果。
我不知道我的代码问题出在哪里。
这是
Modal
组件的代码。
Modal.jsx:
import React, { useState } from "react";
import "./Modal.css";
export default function Modal() {
const [modal, setModal] = useState(false);
const toggleModal = () => {
setModal(!modal);
};
return (
<div>
<button onClick={toggleModal} className="btn-modal">
Open Modal
</button>
{modal && (
<div className="modal">
<div onClick={toggleModal} className="overlay"></div>
<div className="modal-content">
<h2>Hello Modal</h2>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Provident
perferendis suscipit officia recusandae, eveniet quaerat assumenda
id fugit, dignissimos maxime non natus placeat illo iusto!
Sapiente dolorum id maiores dolores? Illum pariatur possimus
quaerat ipsum quos molestiae rem aspernatur dicta tenetur. Sunt
placeat tempora vitae enim incidunt porro fuga ea.
</p>
<button className="close-modal" onClick={toggleModal}>
CLOSE
</button>
</div>
</div>
)}
</div>
);
}
模态.css
body.active-modal {
overflow-y: hidden;
}
.btn-modal {
padding: 10px 20px;
display: block;
margin: 100px auto 0;
font-size: 18px;
}
.modal, .overlay {
width: 100vw;
height: 100vh;
top: 0;
left: 0;
right: 0;
bottom: 0;
position: fixed;
}
.overlay {
background: rgba(49,49,49,0.8);
}
.modal-content {
position: absolute;
top: 40%;
left: 50%;
transform: translate(-50%, -50%);
line-height: 1.4;
background: #f1f1f1;
padding: 14px 28px;
border-radius: 3px;
max-width: 600px;
min-width: 300px;
}
.close-modal {
position: absolute;
top: 10px;
right: 10px;
padding: 5px 7px;
}
也许使用 useRef 而不是 useState。
import React, { useState, useRef } from "react";
const modal = useRef(null);
function toggleDialog(){
if(!modal.current){
return;
}
modal.current.hasAttribute("open")? modal.current.close() : modal.current.showModal();
}