Этого можно добиться, добавив событие 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>
)
}