如何通过react js中的map方法仅访问一项

2023-11-27

我的问题可能不清楚,但这是我的问题。这是我使用 map 方法从数组中获取的卡片,并在每张卡片上显示每个项目。 我已经触发了“编辑”按钮,以便它显示隐藏的文本(只想在一张卡片中看到它)。但是,当我仅单击一张卡片时,所有卡片都会显示该隐藏消息。你能帮我么?

我想在单击编辑按钮的卡片中看到“只想在一张卡片中看到此内容”文本

这是我的代码:

const [edit, setedit]= useState(false)  

<Grid container spacing={5} className="main-grid" >
{allitems.map((oneitem, index) => {
return (
<Grid item key={index} md={3} className="itemGrid" >
<Card className="card">
<CardContent>
<Typography className="" color="textSecondary" gutterBottom>
{oneitem.title}
</Typography>/
<p variant="h5" component="h2" className="description">
{oneitem.description}
</p>
<p className="" color="textSecondary">
Created At: {oneitem.createdAt}
</p>
<Button size="small" onClick={()=> deleted(oneitem._id)} >Delete</Button>
<Button size="small" onClick={()=>setedit(!edit)} >Edit</Button>  <-here is the problem
{edit && <h1>Want to see this in only one card</h1>}   
</CardContent>

这是图像


Issue

您正在使用单个布尔值edit状态值触发所有映射元素的编辑模式。

Solution

使用一些edit声明您可以与数据关联,例如索引或项目id财产。由于我没有看到任何 GUID 使用,因此我将使用 index.html 进行演示。

  1. 使用元素索引来标识什么处于“编辑”模式,null 表示没有任何内容具有“编辑”模式。

     const [editIndex, setEditIndex]= useState(null);
    
  2. 更新切换按钮以切换新索引或返回 null(如果单击同一按钮)

     <Button
       size="small"
       onClick={() => setEditIndex(editIndex => editIndex === index ? null : index)}
     >
       Edit
     </Button>
    
  3. 匹配保存的editIndexstate 到当前映射的元素以有条件地呈现消息。

     {editIndex === index && <h1>Want to see this in only one card</h1>}
    

附加说明

我看到你有一个删除按钮:

<Button size="small" onClick={()=> deleted(oneitem._id)} >Delete</Button>

如果您要从基础数据中删除元素,那么您将需要not使用数组索引作为 React 键。相反,您应该使用唯一标识属性,例如_id,每个元素(他们只需要在兄弟姐妹中是独一无二的)。因此,您不应使用索引来设置“编辑”模式,而是使用_id反而。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何通过react js中的map方法仅访问一项 的相关文章