簡體   English   中英

反應,從另一個函數訪問componentDidMount中定義的變量

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

我正在嘗試在React中構建一個響應式下拉導航欄,並且遇到了障礙。 我在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"); } }); } 

我正在嘗試在同一React組件的onClick函數中訪問它們

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

該變量記錄為未定義。

因此,我的問題是,如何訪問在compnentDidMount中定義的變量?

謝謝

componentDidMount范圍內定義的變量將保留在該函數本身內。 您需要將它們分配給類實例,例如

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