React Error annot read property' onChange'未定义的

时间:2016-09-09 04:30:51

标签: javascript reactjs properties undefined

React Error无法读取属性' onChange'未定义的     app类正在调用Breakpoint组件的映射

 <Breakpoints  key={breakpoint.key}
           name={breakpoint.name}
           minWidth={breakpoint.minWidth}
           onChange={function () {   // this is where react says my error is
           this.onChange(breakpoint)
           }.bind(this)}/>

这是父方法

`onChange(breakpoint) {
    this.props.breakpoints[breakpoint.key].name = name;
    this.state (this.state);
    console.log(breakpoint)
 }`

这些是子元素

<input type="text" name="name" defaultValue={this.state.name}  onBlur={this.onChange}/>
<input type="text" name="minWidth" defaultValue={this.state.minWidth} onBlur={this.onChange}/>

这就是我正在观看并尝试更新代码的方式

onChange(e) {
    e.preventDefault();
    this.setState(
      {[e.target.name]: e.target.value},
      function () {
        console.log(this.state.name);
        this.props.onChange({
          key: this.state.key,
          name: this.state.name,
          minWidth: this.state.minWidth
        });
      }
    );
    }

1 个答案:

答案 0 :(得分:1)

失败发生在我认为的最后一段代码片段中,请参阅我添加的注释行:

onChange(e) {
e.preventDefault();
this.setState(
  {[e.target.name]: e.target.value},
  function () {
    // HERE: "this" is newly created for this function, so this.props is undefined, so this.props.onChange fires an error
    console.log(this.state.name);
    this.props.onChange({
      key: this.state.key,
      name: this.state.name,
      minWidth: this.state.minWidth
    });
  }
);
}

修复程序也是将该函数包装在绑定中,或者使用es2015胖箭头函数,这需要进行babel转换或用户只使用现代浏览器。您也可以使用var self = this技巧。以下是三个选项:

// bind
onChange(e) {
e.preventDefault();
this.setState(
  {[e.target.name]: e.target.value},
  function () {
    console.log(this.state.name);
    this.props.onChange({
      key: this.state.key,
      name: this.state.name,
      minWidth: this.state.minWidth
    }.bind(this));
  }
);
}
// es2015 arrow functions
onChange(e) {
e.preventDefault();
this.setState(
  {[e.target.name]: e.target.value},
  () => {
    console.log(this.state.name);
    this.props.onChange({
      key: this.state.key,
      name: this.state.name,
      minWidth: this.state.minWidth
    });
  }
);
}
// self trick
onChange(e) {
e.preventDefault();
var self = this;
this.setState(
  {[e.target.name]: e.target.value},
  function () {
    console.log(self.state.name);
    self.props.onChange({
      key: self.state.key,
      name: self.state.name,
      minWidth: self.state.minWidth
    });
  }
);
}