作者:ruirui2011幸福 | 来源:互联网 | 2022-12-07 11:09
我正在使用反应,我试图简单地显示我的弹出窗口,但我有这个错误
Uncaught TypeError: Cannot set property 'onclick' of null
at eval (index.js:33)
at Object../src/index.js (main.js:680)
at __webpack_require__ (main.js:20)
at eval (index.js:9)
at Object../examples/src/index.js (main.js:97)
at __webpack_require__ (main.js:20)
at eval (webpack:///multi_(:3001/webpack)-dev-server/client?:2:18)
at Object.0 (main.js:702)
at __webpack_require__ (main.js:20)
at main.js:84
这是我的完整index.js
import React from 'react';
import './style.scss';
import ReactDOM from "react-dom";
const modal = document.getElementById('myModal');
const btn = document.getElementById("myBtn");
const span = document.getElementsByClassName("close")[0];
btn.Onclick= function() {
modal.style.display = "block";
};
span.Onclick= function() {
modal.style.display = "none";
};
window.Onclick= function(event) {
if (event.target === modal) {
modal.style.display = "none";
}
};
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
Open Modal
×
Some text in the Modal..
swedavia
swedish airports
);
}
}
export default MyComponent;
ReactDOM.render(
,
document.getElementById('root')
);
我不明白为什么我有这个错误,请帮帮我!
也许是因为我使用简单的Javascript ...
对不起,如果这是一个愚蠢的问题...但有时我真的不明白容易的事情.
1> Mayank Shukl..: 这是因为,您尝试在实际创建之前将click处理程序附加到元素.这就是为什么,它抛出错误:
未捕获的TypeError:无法设置null的属性'onclick'
使用componentDidMount 生命周期方法确保在附加单击处理程序时将创建元素.
像这样:
componentDidMount() {
const modal = document.getElementById('myModal');
const btn = document.getElementById("myBtn");
const span = document.getElementsByClassName("close")[0];
btn.Onclick= function() {
modal.style.display = "block";
};
span.Onclick= function() {
modal.style.display = "none";
};
window.Onclick= function(event) {
if (event.target === modal) {
modal.style.display = "none";
}
};
}
建议:
直接访问dom元素不是一个好方法,更好的方法是使用状态变量并根据该变量应用样式.
像这样:
constructor(){
super();
this.state = {
openModal: false
}
this.handleOpenModel = this.handleOpenModel.bind(this);
this.handlModelClose = this.handlModelClose.bind(this);
}
handleOpenModel() {
this.setState({
openModal: true,
})
}
handlModelClose() {
this.setState({
openModal: false,
})
}
Open Modal
×
Some text in the Modal..