繁体   English   中英

在 React 中将 Props 传递给父组件

[英]Pass Props to parent componenet in React

我正在尝试将id从子组件(和嵌套组件)传递给它的父组件。

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

但是子项中的函数是未定义的,也不能使嵌套子项中的函数可用。

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

任何帮助将不胜感激

我通过将函数更改为 App.js 渲染中的箭头函数来使其工作,如下所示:

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

同样在 Comment 组件中,您需要向子 Comment 组件添加 handleClick 属性,如下所示:

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

所以这个问题很可能是 javascript 中著名的 this 和 bind 问题。

代码沙盒

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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