Calling a function in React

前端 未结 6 1966
感动是毒
感动是毒 2021-02-04 21:55

I\'m a beginner in React, and I\'m a little confused about calling a function in React.

I saw the following ways and I don\'t know when to use each and which one.

<
6条回答
  •  北恋
    北恋 (楼主)
    2021-02-04 22:38

    If you want to call a function options 2 and with some assumptions 5 should work.

    If you want to actually pass a function as a property to some child component so that it could call it later (say to notify your root element on some event) then option 1 (with prebind) and 3 (with defining a variable const {handleAddTodo} = this and prebind :) ) should work

    // this works if handleAddTodo was prebinded or doesn't use this
    handleAddTodo ={this.handleAddTodo} 
    
    // this probably wont work unless handleAddTodo is higher order function that returns another function
    handleAddTodo ={this.handleAddTodo()} 
    
    // This wont work unless you have a var/let/const that is referencing a function
    handleAddTodo ={handleAddTodo} 
    
    // Same as 1
    handleAddTodo ={this.handleAddTodo} 
    
    // 3 and 2 combined
    handleAddTodo ={handleAddTodo()} 
    

提交回复
热议问题