[英]React - click handler on child component with map not working
我有3个React组件-一个容器(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>
);
}
}
这是我的postList:
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)->通过道具传递(PostList)->通过道具传递(SearchBarContainer)
因为您将箭头函数与onClick一起使用,而不是在此处从其主体调用props.onClick
函数:
onClick={() => props.onClick}
使用这个put ()
:
onClick={() => props.onClick()}
或不使用箭头功能直接编写:
onClick = {props.onClick}
更新:
无论我们传递什么道具,它都将仅成为对象的属性值,我们需要在Child组件中使用它。
您在PostItem
中传递了onClick函数,但在PostItem
中却未在任何地方使用它,请在任何DOM节点上定义click事件,如下所示:
<div onClick={singlePost.onClick} ....>
我认为您已将onClick传递给以下行中的组件PostItem:
return <PostItem key={singlePost.id} post={singlePost} onClick={() => props.onClick}/>
您应该将其作为道具传递给PostItem组件并在那里进行处理。 就像您正在传递密钥和帖子一样。 也为onClick做到这一点,例如:
return <PostItem key={singlePost.id} post={singlePost} onClick={props.onClick}/>
并处理PostItem组件中的onClick属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.