【问题标题】:Uncaught TypeError: Cannot read property 'props' of null in React未捕获的类型错误:无法在 React 中读取 null 的属性“props”
【发布时间】:2017-03-23 19:18:06
【问题描述】:

这是我的子组件,需要将数据向上传递给它的父组件。

class Sidebar extends React.Component {

  getUserInput(event){
    event.preventDefault();
    let value = document.getElementById('input-button').value;
    console.log(value);
    this.props.handleSubmit(value);
  }


  render() {
    return (
      <div>
          <input type="text" id="input-button" placeholder="YGUID" />

            <button type="button" className="btn btn-info btn-icons" onClick={this.getUserInput} />

      </div>
    );

  }
}

Sidebar.propTypes = {
  handleSubmit: React.PropTypes.func
};

这是父进程调用handleSubmit的地方。

......
handleSubmit(data){
    console.log(data);
  }
  render(){
    return(
        <div className="col-md-2 left-pane">
          <Sidebar handleSubmit= {this.handleSubmit}/>
        </div>

    );
  }

我收到以下错误。

Uncaught TypeError: Cannot read property 'props' of null

我在这里做错了什么。

【问题讨论】:

  • console.log(this)getUserInput 函数中返回什么?请这个this post

标签: javascript reactjs


【解决方案1】:

this.getUserInput 传递给 Sidebar 属性的函数在调用时未绑定到正确的上下文 (this)。你可以例如bind它:

<Sidebar handleSubmit={this.handleSubmit.bind(this)}/>

还有其他选择如何解决这个问题。例如使用具有词法this 的箭头函数、在构造函数中绑定方法或使用类属性来定义带有箭头函数的方法(ES7)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 2022-01-19
    • 2021-12-01
    相关资源
    最近更新 更多