gpt4 book ai didi

javascript - 如何在 React.js 中组件之间进行无流量通信

转载 作者:行者123 更新时间:2023-11-28 19:15:08 25 4
gpt4 key购买 nike

好吧,我确实知道通过 refs 在父子之间进行通信或使用 this.props.onClick = {this.props.onClick},我陷入了困境祖 parent 和 child 之间的沟通是这样的:

假设我们有一些博客,一旦我们点击一​​个博客标题,就会显示相应的博客内容,所以我们创建三个组件:BlogAdmin、BlogTitle和Blog(这里只关注BlogAdmin和BlogTitle)

当点击BlogTitle时,我想通知BlogAdmin设置currentblog来指定博客。但我陷入了如何传递数据以及如何触发事件的困境,最好不要使用 pubSub。

下面是我的示例,我删除了一些数据获取/设置和语法以使其清晰。

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

最佳答案

简单的解决方案是添加一个回调函数并将其一路向下发送,如下所示:

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

关于javascript - 如何在 React.js 中组件之间进行无流量通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30017309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com