在我的渲染方法中,我有组件
<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
});
}
},
当我尝试使用此组件加载页面时,我收到错误
无法读取未定义的属性“目标”
我究竟做错了什么 ?
问题是您正在调用此行中的函数:
onChange={this.handleChange()}
您所要做的就是将函数作为值传递给onChange而不调用它。
onChange={this.handleChange}
当您使用括号时,您将调用函数/方法而不是将其与事件处理程序绑定。比较以下两个例子:
//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
如果您使用箭头函数传递事件,则应尝试以下操作:
onChange={(e) => handleChange(e)}
只需这样做
<DatePicker selected={this.state.startDate} onChange={this.handleChange}/>
它会自动传递函数的事件参数。你的其余代码还可以。
您正在执行函数而不是将其作为道具传递。
你需要改变这个,
onChange={this.handleChange()}
有了这个,
onChange={this.handleChange}
如果以上所有建议都不起作用,将此onChange={this.handleChange}
更改为此onChange={() => this.handleChange()}
也可能会有所帮助。