简体   繁体   English

反应,从另一个函数访问componentDidMount中定义的变量

[英]React, accessing variable defined in componentDidMount from another function

I am trying to build a responsive drop down navbar in React and have come to a roadblock. 我正在尝试在React中构建一个响应式下拉导航栏,并且遇到了障碍。 I have these variables defined in componentDidMount 我在componentDidMount中定义了这些变量

 componentDidMount = () => { let nav = document.getElementById("topNav") let main = document.getElementById("main") let menu = document.getElementsByClassName("menuitems") let close = document.getElementById("closeBtn") nav.style.height = "50px"; main.style.marginTop = "50px"; for (let i = 0; i < menu.length; i++) { menu[i].style.marginTop = "100px"; }; close.addEventListener("click", function () { const menuIcon = close.children; for (let i = 0; i < menuIcon.length; i++) { menuIcon[i].classList.toggle("active"); } }); } 

and I am attempting to access them in an onClick function on the same react component here 我正在尝试在同一React组件的onClick函数中访问它们

 navToggle = () => { console.log(this.nav) } 

the variable is logged as undefined. 该变量记录为未定义。

So, my question, how can I access variables that are defined in the compnentDidMount? 因此,我的问题是,如何访问在compnentDidMount中定义的变量?

thank you 谢谢

Variabled defined within the scope of componentDidMount will stay within that function itself. componentDidMount范围内定义的变量将保留在该函数本身内。 You need to assign them to the class instance like 您需要将它们分配给类实例,例如

componentDidMount = () => {
    this.nav = document.getElementById("topNav")
    this.main = document.getElementById("main")
    this.menu = document.getElementsByClassName("menuitems")
    this.close = document.getElementById("closeBtn")


    this.nav.style.height = "50px";
    this.main.style.marginTop = "50px";
    for (let i = 0; i < menu.length; i++) {
        this.menu[i].style.marginTop = "100px";
    };

    this.close.addEventListener("click", function () {
        const menuIcon = this.close.children;
        for (let i = 0; i < menuIcon.length; i++) {
            menuIcon[i].classList.toggle("active");
        }
    });
}

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

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