[英]ReactJS TypeError: Cannot set property 'onclick' of null
I want to implement a modal box
in React and done to following a tutorial from W3Schools .我想在 React 中实现一个
modal box
,并按照W3Schools的教程完成。 The modal is a dialog box/popup window that is displayed on top of the current page:模态是显示在当前页面顶部的对话框/弹出窗口:
But I have error
.但我有
error
。 Here's the error and codes:这是错误和代码:
2. App.js: 2.App.js:
import './App.css';
function App() {
// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
return (
<>
<div className="topnav" id="myTopnav">
<a href="#home" className="active">Forum Anak IT</a>
<a href="#" id="myBtn" className="button">Login</a>
</div>
<div id="myModal" className="modal">
<div className="modal-content">
<span className="close">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
</>
);
}
}
export default App;
You should use state to manage opening and closing state of your modal and fire an onClick event on your button.您应该使用 state 来管理模式的打开和关闭状态,并在按钮上触发 onClick 事件。
function App() {
const [open,setOpen]=useState(false);
return (
<>
<div className="topnav" id="myTopnav">
<a href="#home" className="active">Forum Anak IT</a>
<a href="#" id="myBtn" className="button" onClick={()=>{setOpen(true}}>Login</a>
</div>
{ open &&
<div id="myModal" className="modal">
<div className="modal-content">
<span className="close">×</span>
<p>Some text in the Modal..</p>
</div>
<button onClick={()=>{setOpen(false)}}>Close</button>
</div>
}
</>
);
}
}
export default App;
I grab code from @SiddhantVarma answer, and I modified and add what's missing:我从@SiddhantVarma 答案中获取代码,然后修改并添加了缺少的内容:
import {useState} from "react"
function App() {
const [hidden, setHidden] = useState(true);
return (
<>
<div className="topnav" id="myTopnav">
<a href="#home" className="active">Forum Anak IT</a>
<a href="#" id="myBtn" className="button" onClick={()=>{setOpen(true}}>Login</a>
</div>
{hidden ? (
<></>
) : (
<div id="myModal" className="modal">
<div className="modal-content">
<span className="close">×</span>
<p>Some text in the Modal..</p>
</div>
<button onClick={() => setHidden(true)}>Close</button>
</div>
}
</>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.