Javascript 无法读取未定义的属性“目标”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46389220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:25:23  来源:igfitidea点击:

Cannot read property 'target' of undefined

javascriptreactjs

提问by Alexey K

In my render method I have component

在我的渲染方法中,我有组件

<DatePicker selected={this.state.startDate} onChange={this.handleChange()}/>

handleChange is following

handleChange 如下

handleChange: function (e) {
  var that = this;
  console.log(e.target.value)
  return function () {
    that.setState({
      startDate: e.target.value
    });
  }
},

By when I try to load page with this component, I get error

当我尝试使用此组件加载页面时,出现错误

Cannot read property 'target' of undefined

无法读取未定义的属性“目标”

What am I doing wrong ?

我究竟做错了什么 ?

回答by Matthew Barbara

The problem is that you are invoking the function in this line:

问题是您正在调用此行中的函数:

onChange={this.handleChange()}

All you have to do is simply pass the function as a value to onChange without invoking it.

您所要做的就是将函数作为值传递给 onChange 而无需调用它。

onChange={this.handleChange}

When you use parenthesis you'd be invoking a function/method instead of binding it with an event handler. Compare the following two examples:

当您使用括号时,您将调用一个函数/方法,而不是将其与事件处理程序绑定。比较以下两个例子:

//invokes handleChange() and stores what the function returns in testA.
const testA = this.handleChange()  

vs

对比

//stores the function itself in testB. testB be is now a function and may be invoked - testB();
const testB = this.handleChange 

回答by Andreas Bigger

If you are passing event using an arrow function, you should try the following:

如果您使用箭头函数传递事件,您应该尝试以下操作:

onChange={(e) => handleChange(e)}

回答by bennygenel

You are executing function rather than passing it as a prop.

您正在执行函数而不是将其作为道具传递。

You need to change this,

你需要改变这个,

 onChange={this.handleChange()}

with this,

有了这个,

 onChange={this.handleChange}

回答by Adeel Imran

Simply do this

只需这样做

<DatePicker selected={this.state.startDate} onChange={this.handleChange}/>

It will pass the event param of the function automatically. The rest of your code is okay.

它将自动传递函数的事件参数。你的其余代码没问题。

回答by Master Ace

Changing this onChange={this.handleChange}to this onChange={() => this.handleChange()}may also help if all the suggestions above don't work.

这个改变onChange={this.handleChange}这个onChange={() => this.handleChange()}也可以帮助,如果以上所有建议不起作用。