简体   繁体   中英

Uncaught TypeError: Cannot read property 'props' of null in React

This is my child component that needs to pass data up to its parent.

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

This is where the parent is calling handleSubmit.

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

    );
  }

I get the following error.

Uncaught TypeError: Cannot read property 'props' of null

What am I doing wrong here.

this.getUserInput function passed to the Sidebar props is not bound to the correct context ( this ) when it is called. You can for example bind it:

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

There are also other options how to sovle this. For example using arrow functions which has lexical this , binding methods in constructor or using class properties to define methods with arrow functions (ES7).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM