简体   繁体   中英

How to communicate between Components with out flux in React.js

Ok, I do know through refs communicate between parent and child or use this.props.onClick = {this.props.onClick} , I got stuck in situation communicate between grandparent and child like this:

Says we have some blogs, once we click a blog title, the corresponding blog content will show, so we create three components: BlogAdmin, BlogTitle and Blog (Here let's just focusing on BlogAdmin and BlogTitle)

When BlogTitle is clicked, I want to notify BlogAdmin set currentblog to specify blog. But I got stuck on how to pass the data and how to trigger the event, better with out using pubSub.

Below is my example, I removed some data get/set and grammars making it clear.

var BlogTitle = React.createClass({
  render: function() {
    return
      <li>{this.props.blog.title}</li>
  }
});

var BlogTitles = React.createClass({
  render: function() {
    return 
      <ul>
        {this.state.blogs.map}
          <BlogTitle blog={blog} />
  }
})

var BlogAdmin = React.createClass({
  render: function() {
    return 
      <BlogTitles />
      <BlogContent />
  }
})

The easy solution is to add a callback function and send it down all the way like this:

var BlogTitle = React.createClass({
  render: function() {
    return
      <li onClick={this.handleTitleClick}>{this.props.blog.title}</li>
  },

  handleTitleClick: function() {
      this.props.onBlogTitleSelection(this.props.blog);
  }
});

var BlogTitles = React.createClass({
  render: function() {
    return 
      <ul>
        {this.state.blogs.map}
          <BlogTitle blog={blog} onBlogTitleSelection={this.props.onBlogTitleSelection} />
  }
})

var BlogAdmin = React.createClass({
  selectBlogTitle: function(blog) {
    // act!
  },

  render: function() {
    return 
      <BlogTitles onBlogTitleSelection={this.selectBlogTitle} />
      <BlogContent />
  }
})

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