简体   繁体   中英

Pass Props to parent componenet in React

I'm trying to pass id from child component(and nested component) to it's parent.

var Comment = React.createClass({
handleClick: function(id){
                console.log(this.props, id)
       this.props.handleClick(this.props.comment.id)
   },
  render: function() {
    var comment = this.props.comment
    return <div className="Comment">
      <div onClick={()=> this.handleClick(comment.id)} dangerouslySetInnerHTML={{__html: comment.comment_text}}/>
      {comment.children.length > 0 && comment.children.map(function(child) {
        return <Comment key={child.id} comment={child}/>
      })}
    </div>
  }
})

but the function in child it's undefined and also not to make function availble in nested child.

https://jsfiddle.net/yk5nomzb/1/

Any help would be appreciate it

I made it work by changing the function into an arrow function inside the App.js render like this:

  render() {
    return (
      <div>
        {this.props.comments.map(comment => {
          return (
            <Comment key={comment.id}
              handleClick={this.handleClick}
              comment={comment}
            />
          );
        })}
      </div>
    );
  }

Also in the Comment component, you need to add handleClick prop to the child Comment components like this:

  render() {
    var comment = this.props.comment;
    return (
      <div className="Comment">
        <div
          onClick={() => this.handleClick(comment.id)}
          dangerouslySetInnerHTML={{ __html: comment.comment_text }}
        />
        {comment.children.length > 0 &&
          comment.children.map(child => {
            return (
              <Comment
                key={child.id}
                handleClick={this.props.handleClick}
                comment={child}
              />
            );
          })}
      </div>
    );
  }

So the problem is likely the famous this and bind issue in javascript.

Codesandbox

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