[英]Show/Hide an element programatically in a list of items
我在玩 React,我有一个这样的元素列表:
{posts.map((post) => (
<div className ="hidden" key={post.key}></div>
<button onClick = {() => showMore()}>Click to Show</button>
))}
帖子是 json 对象的列表。 这个想法是只显示帖子的简短描述,当单击按钮时,它会显示整个正文。
posts = [{
"title": "Title",
"description": "",
"thumbnail": 'images/image.png',
"body": "",
"id": 1
}]
我想在单击它的按钮时显示该特定帖子。 使用 document.getElementById 很容易做到这一点,但我无法使用 React 做到这一点。
我能想到的唯一方法是所有帖子都使用一个 useState ,但这不是我想要的。
这与仅显示或隐藏单个元素不同,因为在这种情况下,我不能只创建单个 useState。 我想我可以创建与帖子一样多的 useState,但我真的不知道这将如何工作。
谢谢!
我解决这个问题的方法是创建一个具有内部 state 的 Post 组件:
const Post = ({ post }) => {
const [showMore, setShowMore] = useState(false);
const handleShowMore = () => setShowMore((prevShowMore) => !prevShowMore);
return (
<div class="post" key={post.id}>
<p>{showMore ? post.description : post.description.substring(0, 10)}</p>
<button onClick={handleShowMore}>
Show {showMore ? "Less" : "More"}
</button>
</div>
);
};
如果showMore
为 false(默认为 false),它将仅显示字符串的前 10 个字符。 如果为真,它将显示整个字符串。
然后在您的父组件中,我将 map 覆盖帖子并渲染 Post 组件:
const ParentComponent = () => {
return (
<div className="container">
{data.map((post) => (
<Post post={post} />
))}
</div>
);
};
这是一个例子: https://codepen.io/AliKlein/pen/KKajvOW
这是否接近您想要完成的目标?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.