簡體   English   中英

Typescript function 找不到變量。 '找不到名稱'高度'.ts(2304)'

[英]Typescript function can't find variable. 'Cannot find name 'height'.ts(2304)'

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-portfolio',
  templateUrl: './portfolio.component.html',
  styleUrls: ['./portfolio.component.css']
})
export class PortfolioComponent implements OnInit {

  height = window.innerHeight;
  windowHeight: any;

  constructor() {
   }


  ngOnInit(): void {

    const button = document.getElementById("btn");
    button?.addEventListener("click", this.listenerFunction);

    const button2 = document.getElementById("btn2");
    button2?.addEventListener("click", this.listenerFunctionButton);
  }

  listenerFunction(this: HTMLElement, ev: Event) {
    ev.preventDefault();
    console.log("clicked");
    window.scrollTo({top:height, behavior:'smooth'})
    this.height+= 100;
  }

  listenerFunctionButton(this: HTMLElement, ev: Event) {
    const height = window.innerHeight;
    ev.preventDefault();
    console.log("clicked");
    window.scrollTo({top:-height, behavior:'smooth'})
  }

}

我目前正在實現兩個按鈕以相應地向上/向下滾動。 現在他們正在工作,但我只能向下滾動一屏然后向上滾動一屏,我的某些頁面比一頁長,所以顯然我希望能夠再次按下它並向下滾動。

我遇到的問題似乎很微不足道,但它違背了我習慣的一切。 您可以在圖像中看到我正在嘗試創建一個變量,然后在 function 中使用它來根據按下按鈕的次數增加我的高度。 出於某種原因,它不允許我在 function 中使用我的“高度”變量。 我已經嘗試在構造函數上方初始化我的“高度”,但我得到了一個不同的錯誤。 “類型'HTMLElement'.ts(2339)上不存在屬性'height'”我覺得我錯過了一些非常明顯的東西。 感謝您的任何幫助,您可以提供。

TLDR:不能在 function 中使用局部變量。

您的代碼有多個錯誤之處。 您在構造函數中聲明了height變量。 因此它在 scope 之外不可用。 您應該將高度聲明為 class 的屬性,以便您可以在組件內部訪問它。 此外,您將this作為 class 方法的參數傳遞。 不要將保留關鍵字用作 arguments。 您還可以直接訪問 DOM (document.querySelector()),這在 Angular 中是一種不好的做法,原因有幾個。 您需要改用 angular 提供的抽象。

Angular 是一個非常強大的框架,但它需要對 JavaScript 有很好的了解。 我建議你在使用 TS 和 Angular 之前先提高你的 JS 知識。

使用this而不是let通過構造函數中的變量聲明,並在構造函數之外添加一個類變量。

因此,您將外部變量聲明為類變量(因此您也可以從 HTML 文件中訪問該變量),並在構造函數中初始化變量,如下面的代碼所示

export class PortfolioComponent implements OnInit {

  public height: any;

  constructor() {
      this.height = windows.innerHeight;
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM