无法读取未定义的属性“目标" [英] Cannot read property 'target' of undefined

查看:61
本文介绍了无法读取未定义的属性“目标"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my render method I have component

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

handleChange正在关注

handleChange is following

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

我在做什么错了?

推荐答案

问题是您正在以下行中调用函数:

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

onChange={this.handleChange()}

您要做的只是将函数作为值传递给onChange而不调用它.

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

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 

这篇关于无法读取未定义的属性“目标"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆