javascript - 在 React 中嵌套三个组件

标签 javascript json reactjs components

我试图将函数deleteComment()从父组件传递到子组件,以便当单击子组件时,它将运行deleteComment()。正如您所看到的,我在 CommentBox 中定义了 deleteComment() 并将其传递给 CommentList 组件,然后传递给 Comment 组件。当我尝试仅将其传递到 CommentList 一次时,onClick 事件起作用并删除注释运行,但是一旦我将其传递到另一个级别,它就不会运行。在嵌套多个组件时我是否错误地引用了该函数?

var Comment = React.createClass({
  rawMarkup: function() {
    var rawMarkup = marked(this.props.children.toString(), {sanitize: true});
    return { __html: rawMarkup };
  },
  render: function() {
    return(
      <div className="comment" onClick={this.props.onDeleteComment}>
        <h3 className="commentTag"><span className="commentTitle">{this.props.title}</span> by <span className="commentAuthor">{this.props.author}</span><i className="fa fa-times"></i></h3>
        <div className="commentBody"><span dangerouslySetInnerHTML={this.rawMarkup()}/></div>
      </div>
    );
  }
});

var CommentList = React.createClass({
  render: function() {
    var commentNodes = this.props.data.map(function(comment) {
     return (
       <Comment author={comment.author} key={comment.id} title={comment.title}>
         {comment.text}
       </Comment>
     );
   });
   return(
     <div className="commentList" onDeleteComment={this.props.onDelete}>
        {commentNodes}
     </div>
   )
  }
});

var CommentBox = React.createClass({
  loadCommentsFromServer: function() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  handleCommentSubmit: function(comment) {
     var comments = this.state.data;
     comment.id = Date.now();
     var newComments = comments.concat([comment]);
     this.setState({data: newComments});
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      type: 'POST',
      data: comment,
      success: function(data) {
        this.setState({data: comments});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  deleteComment: function() {
    alert("test");
  },
  getInitialState: function() {
    return {data: []};
  },
  componentDidMount: function() {
   this.loadCommentsFromServer();
    setInterval(this.loadCommentsFromServer, this.props.pollInterval);
 },
  render: function() {
    return(
      <div className="commentBox">
        <ul className="mainBar">
          <li className="active">Updates</li>
        </ul>
        <CommentForm onCommentSubmit={this.handleCommentSubmit}/>
        <CommentList data={this.state.data} onDelete={this.deleteComment}/>
      </div>
    );
  }
});

ReactDOM.render(
  <CommentBox url="/api/comments" pollInterval={500} />,
  document.getElementById('content')
);

最佳答案

CommentList 正在呈现

return( 
  <div className="commentList" onDeleteComment={this.props.onDelete}>
    {commentNodes}
  </div>
)

您希望将 onDeleteComment 传递给您的 Comment,而不是包装它们的 div。

但是由于它是使用匿名函数进行 .map 处理的,因此作用域发生了变化。告诉它 this 应该与 .bind

一起使用
  this.props.data.map(function(comment) {
   return (
     <Comment author={comment.author} key={comment.id} title={comment.title} onDeleteComment={this.props.onDelete}>
       {comment.text}
     </Comment>
   );
  }.bind(this))

关于javascript - 在 React 中嵌套三个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35402043/

相关文章:

javascript - 通过点击事件移动图像

javascript - 错误消息 : 'Unexpected block statement surrounding arrow body.(箭头主体样式)

java - 如何为此 REST 响应编写 getter setter 类以进行改造

reactjs - React Native TypeError : dispatcher. useSyncExternalStore 不是函数

reactjs - 动态插入将通过 Reactjs 执行的脚本标签

javascript - 如果在输入字段之外按下按键,则不会触发 keyup 事件

javascript - 重点关注按键上的输入类型文本/搜索

javascript - 仅当循环遍历数组时才执行 else 语句

sql - 我如何在 postgresql 中使用更新和 json 填充记录?

java - 将neo4j数据集连接到Web应用程序的最简单方法是?