简体   繁体   中英

TypeError: Cannot read property 'bind' of undefined - ReactJS

I am getting the below error while binding the values to the function.

TypeError: Cannot read property 'bind' of undefined

Please see the code below:

<button className={classes.ButtonStyle} onClick={props.onClickHandler.bind(null,props.id)}>{props.children}</button>

But the arrow function notation is working fine though:

onClick={(e)=>{props.onClickHandler(props.id,e)}}

May I please know where I have done wrong? Also I am not using class based components but only functional based components(hooks).

The onClickHandler function is as below:

const onClickHandler = (id, e) =>{
    e.preventDefault();
    console.log('buttonSetNullHandler', id);
}

It's difficult to know for sure without looking at your program as a whole, but here's what's possibly happening:

  • With the arrow function style, props.onClickHandler is evaluated at the time the button is clicked.
  • With the bind style, the bind will be executed when the component first mounts.

My guess is that when the component first mounts, props.onClickHandler is not set, but it is being set in a subsequent render that happens before you click the button.

It should be easy to check by putting a console.log(props) in the render function and seeing how many times it happens and what the props are each time.


As an aside, I personally would go with the arrow style over the bind style - onClick={e => props.onClickHandler(props.id,e)} is likely to be much less surprising to the developer coming after you. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM