簡體   English   中英

在組件構造函數之外使用時變量未定義

[英]Variable undefined when used outside of component constructor

我正在使用React和Electron進行項目,但出現錯誤。 我有一個帶有構造器的組件,該構造器帶有道具(以兩個變量的形式出現)。該構造器在一個單獨的文件中實例化。 問題是該變量在構造函數中工作正常(例如,如果執行console.log進行輸出),但在變量之外,該變量未定義返回。

我已經嘗試過使用.bind綁定它,但這沒有幫助,它仍然顯示為undefined。

這是構造函數的調用位置:

const dropDown = new Dropdown({
  editor,
  monaco
});

這是構造函數,以及我嘗試在其中使用變量的示例:

constructor(props) {
  super(props);

  // Define variables
  this.editor = props.editor;
  this.monaco = props.monaco;
  // Returns correct object
  console.log(this.monaco);

  // Bind functions
  this.changeLanguage = this.changeLanguage.bind(this);
  this.filterFunction = this.filterFunction.bind(this);
  this.dropDown = this.dropDown.bind(this);
}

changeLanguage(language) {
  // Returns undefined all the time
  console.log(this.monaco);
  this.monaco.editor.setModelLanguage(this.editor, language);
}

我希望變量在構造函數和文件中其他位置的函數中都相同,但是由於某種原因,它僅在構造函數中定義。

您可以使用this.props.monaco。 或者您可以將道具傳遞給changeLanguage函數(如果您重寫它)

changeLanguage(language, props) {
  // Returns undefined all the time
  console.log(props.monaco);
  props.monaco.editor.setModelLanguage(this.editor, language);
}

並命名為: this.changeLanguage('English', this.props)

暫無
暫無

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

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