簡體   English   中英

為什么我不能使用 function 關鍵字在 reactjs ZA2F2ED4F298EBC2ABB6DZC2 中定義 function

[英]why I can not use function keyword to define a function inside a reactjs class

I have been confused about some syntaxes in ReactJS, one is that when I define a function inside one Reactjs class, I can not use function keyword, but when I moved the function outside the class then I have to add keyword function before the signature. 其次,如果我在 render() 中寫了一個 function,那么我必須使用箭頭 function。 例如,為什么以下是錯誤的:

class Test extends Component{
   constructor(props){
      super(props)
   }
   function test(){
     //this is wrong,I need to remove function keyword
   }

   render(){
     mytest(){
      //also this is wrong,I only can use arrow function
     }
   }
} 

那是因為您的組件基於 class 並且具有方法,而不是功能。 要定義一個方法,你可以這樣做:

class Test extends Component {
  constructor(props) {
    super(props)
  }

  test() { // Defining method

  }

  render() {
    this.test() // can be called like this
  }
} 

如果您希望能夠在組件內定義函數,則需要先將其轉換為函數式:

function Test(props) {
  function test() {
    // This now works
  }
}

因為,你不需要寫 function 關鍵字

完成這個官方教程

暫無
暫無

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

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