Jack
Jack

Reputation: 5880

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. Second is that if I write a function inside the render(), then I have to use arrow function. For example, why the following is wrong:

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
     }
   }
} 

Upvotes: 10

Views: 6294

Answers (1)

Clarity
Clarity

Reputation: 10873

That's because your component is class based and has methods, not functions. To define a method you can do like so:

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

  test() { // Defining method

  }

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

If you want to be able to define functions inside a component you'll need to transform it to functional first:

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

Upvotes: 18

Related Questions