[英]How to render other component from children on onClick event react 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.