简体   繁体   English

TypeError:无法读取未定义的属性“ bind”-ReactJS

[英]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: onClickHandler函数如下:

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. 使用箭头函数样式,单击按钮时将评估props.onClickHandler
  • With the bind style, the bind will be executed when the component first mounts. 使用bind样式时,绑定将在首次安装组件时执行。

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. 我的猜测是,在首次安装组件时,未设置props.onClickHandler ,而是在单击按钮之前发生的后续渲染中将其设置。

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. 通过将console.log(props)放在render函数中并查看它发生了多少次以及每次是什么道具,应该很容易检查。


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. onClick={e => props.onClickHandler(props.id,e)} ,我个人将箭头样式设置为绑定样式onClick={e => props.onClickHandler(props.id,e)}对于onClick={e => props.onClickHandler(props.id,e)}您的开发人员而言, 可能并不那么令人惊讶 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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