首页 > 解决方案 > 如何将参数传递给其他组件以在 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>

  )
 }

谢谢。

标签: javascriptreactjsaxios

解决方案


您可以通过添加 onclick 事件并将处理程序附加到它来实现此目的。然后你可以将该处理程序绑定thispost.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>

  )
 }

推荐阅读