javascript - 如何修复代码,以便仅针对点击的国家/地区显示附加卡?
问题描述
当我单击一个国家的行时,会出现整个国家列表的附加卡。如何使附加卡仅针对点击的国家/地区打开?
/*const countries = useCountry();*/
const [showCard, setShowCard] = useState('none');
const currentView = {
display: showCard
}
const ShowOnClick = () =>{
let display = 'flex'
setShowCard(display)
}
if(!data){
return(
<h1>Loading...</h1>
)
}
return (
<table>
<thead>
<tr>
<th>№</th>
<th>Country</th>
<th>Total Confirmed</th>
</tr>
</thead>
<tbody>
{data.map((country, index) => (
<>
<tr onClick={ShowOnClick} key={index}>
<td>{index + 1}</td>
<td>{country.Country}</td>
<td>{country.TotalConfirmed}</td>
{/*<td className="deaths">{country.TotalDeaths}</td>
<td>{country.TotalRecovered}</td>*/}
</tr>
<div className="card" style={currentView}>
<h4>{country.Country}</h4>
</div>
</>
))}
</tbody>
</table>
)
};```
解决方案
您可以创建一个名为 TableRow 的新组件并在其中包含状态。这样每一行都会有自己的状态。
const TableRow = ({ country, rowNo }) => {
const [showCard, setShowCard] = useState('none');
const ShowOnClick = () =>{
setShowCard(display)
}
return (
<>
<tr onClick={ShowOnClick} key={index}>
<td>{rowNo}</td>
<td>{country.Country}</td>
<td>{country.TotalConfirmed}</td>
{/*<td className="deaths">{country.TotalDeaths}</td>
<td>{country.TotalRecovered}</td>*/}
</tr>
<div className="card" style={{ display: showCard}}>
<h4>{country.Country}</h4>
</div>
</>
)
}
现在您可以将其用作
<tbody>
{data.map((country, index) => (
<TableRow key={index} country={country} rowNo={index + 1} />
))}
</tbody>
这种方法的优点是现在单击一行将仅重新呈现该行而不是所有其他行,如果您的状态位于呈现所有行的组件中,则会发生这种情况。
推荐阅读
- couchdb - couchdb 的 Hyperledger Fabric 性能问题
- java - java中矩阵中的值分配
- java - Spring-integration:如何正确调用 SOAP Web 服务?
- mongodb - 带有父引用的集合的 MongoDB 自连接(聚合)
- wpf - 在纯 XAML 中绘制两个元素之间的连接线
- android - 房间特权与查询的关系
- javascript - 使用对象访问javascript中自调用函数的函数
- wordpress - 在客户的电子邮件中添加链接以在 Woocommerce 中基于订单创建事件
- sql-server - 在发布者上添加列
- swift - 何时应使用异步方法的合适挂钟时间阈值?