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

阿列克谢

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

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

handleChange正在关注

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

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

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

我究竟做错了什么 ?

马修·芭芭拉(Matthew Barbara)

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

onChange={this.handleChange()}

您所要做的只是简单地将函数作为值传递给onChange而不调用它。

onChange={this.handleChange}

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

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章