代码之家  ›  专栏  ›  技术社区  ›  Alexey K

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

  •  16
  • Alexey K  · 技术社区  · 8 年前

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

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

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

    6 回复  |  直到 6 年前
        1
  •  39
  •   Matthew Barbara    8 年前

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

    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 
    
        2
  •  4
  •   Andreas Bigger    7 年前

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

    onChange={(e) => handleChange(e)}
    
        3
  •  0
  •   Adeel Imran    8 年前

    只需这样做

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

    它将自动传递函数的事件参数。剩下的代码没问题。

        4
  •  0
  •   bennygenel    8 年前

    你需要改变这个,

     onChange={this.handleChange()}
    

     onChange={this.handleChange}
    
        5
  •  0
  •   Master Ace    8 年前

    更改此 onChange={this.handleChange} onChange={() => this.handleChange()} 如果以上所有建议都不起作用,可能也会有所帮助。

        6
  •  -1
  •   gtr Developer    5 年前

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