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

Ale*_*y K 7 javascript reactjs

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

<DatePicker selected={this.state.startDate} onChange={this.handleChange()}/>
Run Code Online (Sandbox Code Playgroud)

handleChange正在关注

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

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

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

我究竟做错了什么 ?

Mat*_*ara 20

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

onChange={this.handleChange()}
Run Code Online (Sandbox Code Playgroud)

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

onChange={this.handleChange}
Run Code Online (Sandbox Code Playgroud)

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

//invokes handleChange() and stores what the function returns in testA.
const testA = this.handleChange()  
Run Code Online (Sandbox Code Playgroud)

VS

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