【发布时间】:2018-02-08 03:23:03
【问题描述】:
我有 3 个反应组件 - 一个容器 (SearchBarContainer) 和 2 个展示组件(PostList 和 PostItem(PostList 的子项))
我正在尝试将点击处理程序附加到将冒泡到 SearchBarContainer 的帖子项目,这是我的代码:
class SearchBarContainer extends Component {
selectPost(post) {
console.log('cliked');
//this.props.dispatch(selectPost(post));
}
render() {
return (
<div>
<div className="center-xs">
<p>To get started, type in some keywords below</p>
</div>
<SearchBar onTermChange={this.props.actions.loadPosts} onNull={this.props.actions.nullPosts}/>
<PostList posts={this.props.posts} isFetching={this.props.isFetching} onClick={this.selectPost}/>
</div>
);
}
}
这是我的帖子列表:
const PostList = (props) => {
const postItems = props.posts.map((singlePost) => {
return <PostItem key={singlePost.id} post={singlePost} onClick={() => props.onClick}/>
});
if(!props.isFetching) {
return (
<div className="mt2 row list-unstyled" > {postItems}</div>
);
} else {
return (
<Loader />
);
}
};
export default PostList;
但是,此点击处理程序不起作用。我注意到如果我将点击处理程序放在包装 postItems 数组的 div 上,那么它确实可以工作,我认为问题是点击处理程序附加到包装在 div 内的映射项目?
这里是 PostItem 函数:
const PostItem = (singlePost) => {
return (
<div className="col-lg-4 col-md-12 mb2 animated fadeIn">
<div className="card rounded">
<div className="card-header p1">
<h4 className="card-title mt0 h5">{singlePost.post.title}</h4>
</div>
<img className="card-img-top img-fluid" src={singlePost.post.thumbnail} alt={singlePost.post.title} />
<div className="card-block p1">
{/*<p className="card-text">{singlePost.post.description}</p>*/}
<Link to={`/product/${singlePost.post.slug}`} className="btn btn--blue flt--left w100">View More</Link>
</div>
</div>
</div>
)
};
export default PostItem;
我想也许我需要点击处理程序事件像这样: 点击(PostItem)->通过props传递(PostList)->通过props传递(SearchBarContainer)
【问题讨论】:
-
除了重复之外,您还需要进行@Mayank 在答案中建议的更改
标签: javascript reactjs