javascript - 未捕获的 TypeError : Cannot set property 'onclick' of null , 无法打开我的弹出窗口

标签 javascript reactjs react-native popup

我正在使用 React,我试图简单地显示我的弹出窗口 onclick 但我有这个错误

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 (
            <div style={{margin:'auto', float:'none'}}>

                <button id="myBtn">Open Modal</button>
                <div id="myModal" className="modal">
                    <div className="modal-content">
                        <span className="close">&times;</span>
                        <p>Some text in the Modal..</p>
                    </div>

                </div>

                <table cellSpacing="0" cellPadding="0" style={{margin:'0 auto',marginBottom:'2rem'}}>
                    <thead>
                    <tr>
                        <td>
                    <span
                        style={{
                            height: '100px',
                            width: '100px',
                            backgroundColor: 'darkgrey',
                            borderRadius: '50%',
                            display: 'inline-block'
                        }}/>
                        </td>
                        <td style={{color:'#2c4e88'}}>
                            <h1><p>swedavia</p></h1>
                            <h2><p>swedish airports</p></h2>
                        </td>
                    </tr>
                    </thead>
                </table>


                <form onSubmit={this.handleSubmit}>
                    <div style={{color:'darkgrey',padding: '16px'}}>
                        <label htmlFor="uname">Username</label>
                        <input type="text" value={this.state.value} onChange={this.handleChange} />
                        <label htmlFor="psw">Password</label>
                        <input type="password" name="psw" required/>
                        <div style={{marginTop:'2rem'}}>
                            <button type="submit">ОТПРАВИТЬ</button>
                            <span style={{float: 'right',paddingTop: '16px'}}><a href="#">Forgot password?</a></span>
                        </div>
                    </div>
                </form>

            </div>
        );
    }
}

export default MyComponent;

ReactDOM.render(
    <MyComponent />,
    document.getElementById('root')
);

我不明白为什么会出现这个错误,请帮助我!

也许是因为我使用的是简单的 javascript...

抱歉,如果这是一个愚蠢的问题......但有时我真的不明白简单的事情。

最佳答案

这是因为,您试图在实际创建元素之前将单击处理程序附加到元素。这就是为什么它会抛出错误:

Uncaught TypeError: Cannot set property 'onclick' of null

使用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,
    })
}

<button id="myBtn" onClick={this.handleOpenModel}>Open Modal</button>

<div
    id="myModal"
    className="modal"
    style={{ display: this.state.openModal ? 'block' : 'none' }}
>
    <div className="modal-content">
        <span className="close" onClick={this.handlModelClose}>&times;</span>
        <p>Some text in the Modal..</p>
    </div>
</div>

关于javascript - 未捕获的 TypeError : Cannot set property 'onclick' of null , 无法打开我的弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51931228/

相关文章:

javascript - 让元素循环出现和消失

javascript - 如何将字符串添加到待办事项列表中的字符串列表 react

react-native - 如何在 ubuntu 19.04 中完全卸载 brew 并重新安装 brew

javascript - 如何在 Angular 中执行带有请求 header 的 ajax post

javascript - 为什么我的 Javascript 函数有时只能工作?

reactjs - React Redux 添加额外的操作字段导致 promise 以不同的方式返回

ios - 如何使用 React Native 重现 iOS 11 map Bottom Sheet

react-native - 如何从本地存储读取文件?

javascript - 想使用ajax获取条件数据

javascript - 将 ref 传递给 hook 问题