【问题标题】:How to add a className to single .map item?如何将 className 添加到单个 .map 项目?
【发布时间】:2021-05-02 05:13:54
【问题描述】:

我想将 className 添加到 .map 项目,但仅限于被点击的项目。

试过 useState ( {state ? "class" : ""} ) 但它为我的循环中的所有项目添加了类。 我也尝试过 useRef,但我了解到 useRef 不会导致重新渲染,因此结果没有在屏幕上更新。

示例代码:

    {posts.map((post)=> {
      return (
        <div className=`PLACE FOR CLASS` key={post.id}>
        {post.title}
        <button onClick={()=> onclick event to add class}>add</button>
        </div>
      )
    })}

那么在这种情况下,只为被点击的项目添加类的方法是什么? (我想我需要使用 Key 但不知道如何使用)

【问题讨论】:

  • post有没有被点击的提示?
  • 我更改 postId 状态以获取点击帖子的 id。 (稍后编辑帖子)

标签: reactjs dom jsx


【解决方案1】:

如果您不想将此信息添加到主状态 (posts),您可以创建一个单独的选定 id 列表,它将是这样的(假设您使用的是函数组件)

const [selectedPosts, setSelectedPosts]=useState([]);
...
{posts.map((post)=> {
  return (
    <div className={selectedPosts.includes(post.id) && "myClass"} key={post.id}>
    {post.title}
    <button onClick={()=> {setSelectedPosts(s => [...s, post.id])}}>add</button>
    </div>
  )
})}

【讨论】:

  • 谢谢,正是我想要的!
猜你喜欢
  • 2020-07-14
  • 1970-01-01
  • 2015-02-01
  • 2012-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多