为什么我不能使用function关键字在reactjs类中定义函数

Jac*_*ack -1 javascript reactjs

我对ReactJS中的某些语法感到困惑,其中之一是,当我在一个Reactjs类中定义一个函数时,我不能使用function关键字,但是当我将该函数移到该类之外时,则必须在签名之前添加关键字function。其次,如果我在render()内编写一个函数,则必须使用箭头函数。例如,为什么以下错误:

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
     }
   }
} 
Run Code Online (Sandbox Code Playgroud)

Cla*_*ity 5

那是因为您的组件是基于类的,并且具有方法,而不是函数。要定义一个方法,您可以这样:

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

  test() { // Defining method

  }

  render() {
    this.test() // can be called like this
  }
} 
Run Code Online (Sandbox Code Playgroud)

如果您希望能够在组件内部定义函数,则需要先将其转换为函数:

function Test(props) {
  function test() {
    // This now works
  }
}
Run Code Online (Sandbox Code Playgroud)