【问题标题】:Cannot read property 'target' of undefined无法读取未定义的属性“目标”
【发布时间】:2017-09-24 10:48:18
【问题描述】:

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

<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
    });
  }
},

当我尝试用这个组件加载页面时,我得到了错误

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

我做错了什么?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    问题是你在这一行调用函数:

    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 
    

    【讨论】:

    • 很好的答案!也帮助了我。
    • 如果要传参数怎么办
    • 像这样 onMouseOver={(event) => { this.moveBall(event) }}
    • @MaxwellLynn 如果你想传递一个参数 - onMouseOver={ (e) => this.moveBall(e) }
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      只需这样做

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

      它会自动传递函数的事件参数。您的其余代码都可以。

      【讨论】:

        【解决方案4】:

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

        你需要改变它,

         onChange={this.handleChange()}
        

        有了这个,

         onChange={this.handleChange}
        

        【讨论】:

        • 现在我收到警告:bind():您正在将组件方法绑定到组件。 React 以高性能的方式自动为您完成此操作,因此您可以安全地删除此调用。请参阅 ClientOrderList 以及当我触发 onChange - TypeError: Cannot read property 'value' of undefined
        • 他不需要绑定。 Bind 适用于函数,而不是方法。看看我的回答
        【解决方案5】:

        如果上述所有建议都不起作用,则将此 onChange={this.handleChange} 更改为 onChange={() =&gt; this.handleChange()} 也可能会有所帮助。

        【讨论】:

        • 这不是一个好主意。设置匿名函数会阻碍 React 的性能。您应该始终使用 this.handleChange 并且永远不要在渲染函数中设置匿名函数,除非您必须(例如传递 args)
        【解决方案6】:

        你可以这样修复它

        function handleChange(event) {
            const value =  event.taget.value;
        }
        
        <input onChange={handleChange} />
        
        not this
        
        <input onChange={handleChange()} />
        

        【讨论】:

        • 欢迎您,感谢您抽出宝贵时间回答这个问题。您能否提供有关您的解决方案的更多详细信息?例如,为什么您的解决方案比被高度接受的答案更好?此外,这个问题是在 3 年前提出并回答的。请务必在回答时查看原始问题的日期。
        猜你喜欢
        • 2020-08-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多