javascript - 如何将参数传递给其他组件以在 react.js 中单击按钮时显示 API 列表的详细信息
问题描述
我是 reactJS 的新手。我制作了一个显示帖子列表的 Listview。我有一个按钮,可以将我带到另一个组件/页面,我想在该组件/页面上显示对该帖子的评论。我如何将 postId 传递给其他组件?以及我将如何将该 id 传递给 API 服务以显示评论详细信息。
这是代码。这是 postComponent,现在我想将 post.id 传递给 commentComponent,并且我想在 ShowComments 按钮单击时加载该页面。
我正在使用 axios 来获取数据。
state = {
posts: []
}
componentDidMount() {
axios.get(`https://jsonplaceholder.typicode.com/posts`)
.then(res => {
const posts = res.data;
this.setState({ posts });
})
}
render() {
return (
<div className="userlist">
<ul>
{ this.state.posts.map((post , index) =>
<li key={post.id}>
<div className="user_name"><span>Post:</span> {post.title}</div>
<div className="user_usernamename"><span>Details:</span>{post.body}</div>
<div className="actionButtons">
<button>Show Comments</button>
<button>Flag</button>
</div>
</li>
)}
</ul>
</div>
)
}
谢谢。
解决方案
您可以通过添加 onclick 事件并将处理程序附加到它来实现此目的。然后你可以将该处理程序绑定this
到post.id
在此处阅读更多信息:https ://reactjs.org/docs/handling-events.html#passing-arguments-to-event-handlers
每当点击帖子时,都会调用此处理程序,您可以在此处内部处理 axios 的调用,或者如果您CommentComponent
生活在父文件中,那么您可以通过道具冒泡点击并让父组件进行 API 调用并最终显示评论。
像这样:
state = {
posts: [],
comments: [],
showComments: false
}
componentDidMount() {
axios.get(`https://jsonplaceholder.typicode.com/posts`)
.then(res => {
const posts = res.data;
this.setState({ posts });
})
}
handleCommentClick (postId) {
// Either set the state and then do a conditional rendering
// or handle this change in the parent component
// if handled in parent component
this.props.handleCommentClick && this.props.handleCommentClick(postId);
// If handling it here then..
// First make the API call using axios
axios.get(`https://jsonplaceholder.typicode.com/comments/${postId}`)
.then(res => {
this.setState({
comments: res.comments,
showComments: true
});
});
}
render() {
return (
<div className="userlist">
<ul>
{ this.state.posts.map((post , index) =>
<li key={post.id}>
<div className="user_name"><span>Post:</span> {post.title}</div>
<div className="user_usernamename"><span>Details:</span>{post.body}</div>
<div className="actionButtons">
<button onClick={this.handleCommentClick.bind(this, post.id)}>Show Comments</button>
<button>Flag</button>
</div>
</li>
)}
</ul>
{
// Whenever show comments is made true, this component will render
showComments &&
<CommentsComponent comments={this.state.comments} />
}
</div>
)
}
推荐阅读
- python - 类的两个实例相等但哈希码不同
- java - 是否有一种简单的方法或函数可以获取数组中所有数字的差、积或商
- sqlite - 如何在 peewee 中用 max() 和 ifnull() 表示选择
- azure-active-directory - 在 Teams 中注册您的应用程序失败,并出现错误“您无权将 Hello World 添加到此团队”。
- ffmpeg - 使用 directshow 输入和 JPEG 图像序列输出为 FFmpeg 启用 QSV
- haskell - (<*) 如何以最佳方式实现序列?
- mysql - MYSQL 在不存在的日期中返回零,并且 COUNT 在特定日期存在多少行
- java - Spring Boot 无法连接 Kubernetes 集群中的 mysql
- nativescript-vue - 发送 POST 请求,接收 PDF 作为回报,并将其保存到 NativeScript 中的文件系统
- r - 将数据框转换为其他数据框,以便能够使用广告牌绘制图表