简体   繁体   English

我想在React中显示一个小吃店

[英]I want to display a Snack Bar in React

This is the function that is being called on a button click. 这是在单击按钮时调用的功能。

handleClick() {
        var x = document.getElementById("snackbar");
        x.className = "show";
        setTimeout(function () {
            x.className = x
                .className
                .replace("show", "");
        }, 3000);
        return (
            <div id="snackbar">DONE</div>
        )
    }

This is my onClick onClick={this.handleClick} 这是我的onClick onClick={this.handleClick}

It shows me an error that"Uncaught (in promise) TypeError: Cannot set property 'className' of null" What am I doing wrong. 它向我显示一个错误:“未捕获(承诺)TypeError:无法将属性'className'设置为null”我在做什么错。 All the help is appreciated. 感谢所有帮助。

TypeError: Cannot set property 'className' of null" TypeError:无法将属性'className'设置为null”

Means that you are trying to access the classname property in a null variable. 意味着您正在尝试访问null变量中的classname属性。

If var x = document.getElementById("snackbar"); 如果var x = document.getElementById("snackbar"); has not results, it will return null, and x will be equal to null. 没有结果,它将返回null,并且x等于null。 Add console.log(x) after var x = document.getElementById("snackbar"); var x = document.getElementById("snackbar");之后添加console.log(x var x = document.getElementById("snackbar"); so you can test if it comes from here. 因此您可以测试它是否来自这里。

It can be caused by: 原因可能是:

Invalid HTML syntax (some tag is not closed or similar error)
Duplicate IDs - there are two HTML DOM elements with the same ID
Maybe element you are trying to get by ID is created dynamically (loaded by ajax or created by script)?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM