繁体   English   中英

如何使用 Card.js 组件上的 onClick 事件在 React 中渲染 Article.js 组件?

[英]How to use onClick event on Card.js component to render Article.js Component in React?

现在我在 Home.js 页面中,我想在用户单击特定卡片(Card.js 组件)时呈现 Article.js 组件/页面。 这是我的 Home.js 代码

const Home = () => {
  const posts = useSelector((state) => state.posts)
  const [currentId, setCurrentId] = useState(null)

  const handleClick = () => {
    return <Article />
  }

  return (
    <div className="container">
      <h4 className="page-heading">LATEST</h4>
      <div className="card-container">
        {
          posts.map(post => <Card key={post._id} post={post} setCurrentId={setCurrentId} onClick={handleClick} />)
        }
      </div>
    </div>
  )
}

另一个问题:如何将后变量发送到 onClick 方法? 当我发送它时,方法被调用。

先感谢您:)

听起来你想使用React 路由器 在我看来,您想将帖子加载为自己的页面吗?

我还应该指出,任何传递给onClick的 function 都不能返回任何东西。 在事件 function 中return的唯一目的是提前退出 function。

要在 click hadler 中传递您想要的参数,可以执行以下操作:

      posts.map(post => 
        <Card 
           key={post._id} 
           post={post} 
           onClick={() => handleClick(post)} />
      )

我同意@Jackson 的观点,你可能想研究一下 React Router。 但你不需要它。 您可以根据currentId有条件地呈现Article组件。

点击处理程序不应返回任何内容。 您可以使用onClick来控制currentId state,而不是从onClick回调中返回<Article /> 您可以传递一个 function ,它根据map中的post变量将currentId设置为 post id,如下所示: onClick={() => setCurrentId(post._id)}

您的Home组件的return将呈现帖子列表或当前帖子,具体取决于您是否有currentId或只有null

const Home = () => {
  const posts = useSelector((state) => state.posts);
  const [currentId, setCurrentId] = useState(null);

  return (
    <div className="container">
      {currentId === null ? (
        // content for list of posts - when currentId is null
        <>
          <h4 className="page-heading">LATEST</h4>
          <div className="card-container">
            {posts.map((post) => (
              <Card
                key={post._id}
                post={post}
                // arrow function takes no arguments but calls `setCurrentId` with this post's id
                onClick={() => setCurrentId(post._id)}
              />
            ))}
          </div>
        </>
      ) : (
        // content for a single post - when currentId has a value
        <>
          <div
            // setting currentId to null exits the aritcle view
            onClick={() => setCurrentId(null)}
          >
            Back
          </div>
          <Article
            // could pass the whole post
            post={posts.find((post) => post._id === currentId)}
            // or could just pass the id and `useSelector` in the Article component to select the post from redux
            id={currentId}
            // can pass a close callback to the component so it can implement its own Back button
            onClickBack={() => setCurrentId(null)}
          />
        </>
      )}
    </div>
  );
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM