请阐明我使用React钩子切换表中特定行的问题。每当我按下click ..时,它会为每一行打开,并且默认情况下,表头向右移动不是恒定的。
toggleHidden(key)中的错误。如何更正我的toggleHidden函数?
const[isHidden , setIsHidden] = React.useState(true)
const toggleHidden = () => setIsHidden(!isHidden)
const data = [
{
"name": "gvf",
"email": "abc",
"companyname": "xyz",
"address": "abcy"
},
{
"name": "abi",
"email": "dhf",
"companyname": "dhd",
"address": "fhfh"
}
]
return (
<div>
<Row>
<Col>
<table className="table table-hover table-striped table-sm">
<thead className="thead-dark">
<tr>
<th>Name</th>
<th>Email</th>
<th>CompanyName</th>
<th>Address</th>
</tr>
</thead>
<tbody>
{data.map((a , key) => (
<tr key={a.name}>
<td><Button onClick = {toggleHidden(key)}>Click</Button>
{!isHidden && <p>Hello ABIII</p> }
</td>
<td>{a.name}</td>
<td>{a.email}</td>
<td>{a.address}</td>
<td>{a.companyname}</td>
</tr>
))}
</tbody>
</table>
</Col>
</Row> </div>
答案 0 :(得分:1)
您需要定义特定行-映射时:
{data.map(a => (
)}
尝试向集合中的每个项目添加键属性,如下所示:
{data.map((a, key) => (
))}
然后传递给您的物品:
<tr key={key}>
所以现在每个都是唯一的-因此,如果您将该键传递给函数:
<Button onClick = {toggleHidden(key)}>
程序应知道哪个特定项目执行toggleHidden
功能