React+Tailwind中为数组内指定卡片添加右侧特殊样式
问题描述
需要为每个卡片的文本元素上方添加彩色线条,且仅第三张(key为3)卡片的右侧额外显示一条相同样式的线条,其余卡片无此右侧线条。已筛选出key为3的数组项,但不清楚如何在React渲染环节结合Tailwind实现样式区分。
解决方案
完全可以通过React的条件渲染结合Tailwind的类名实现,无需额外的filter操作,直接在遍历卡片时判断当前项的key即可:
修改后的完整代码
const TheCards = () => { const items = [ { key: '1', tittle: 'Tittle1', content: 'First Paragraph of content', }, { key: '2', tittle: 'Tittle2', content: 'Second Paragraph of content', }, { key: '3', tittle: 'Tittle3', content: 'Third Paragraph of content.', }, { key: '4', tittle: 'Tittle4', content: 'Fourth Paragraph of content.', }, ] return ( <> <div className="container grid grid-cols-3 gap-x-14 gap-y-28"> {items.map((item) => ( <div key={item.key} className="relative"> {/* 所有卡片的顶部彩色线条 */} <div className="border-t-2 border-blue-500 ml-8 -mr-7"> <div className="bg-blue-500 rounded-full h-8 w-8 -translate-y-5 -translate-x-9 text-white text-center pt-1"> {item.key} </div> </div> {/* 仅key=3的卡片渲染右侧线条 */} {item.key === '3' && ( <div className="absolute right-0 top-0 bottom-0 w-2 border-r-2 border-blue-500"></div> )} <p className="text-2xl font-bold leading-9 text-gray-900 pt-6"> {item.tittle} </p> <p className="pt-4 leading-6 text-gray-200"> {item.content} </p> </div> ))} </div> </> ) } export default TheCards
核心要点
- 条件渲染右侧线条:通过
{item.key === '3' && <元素/>}的短路逻辑,仅在当前卡片key为3时渲染右侧线条,避免样式重复。 - Tailwind样式复用:顶部和右侧线条使用相同的
border-blue-500类名保证样式统一,可根据需求替换为其他颜色类(如border-green-500)。 - 移除冗余代码:原代码中
select变量未实际参与渲染,可直接删除以简化代码。
内容的提问来源于stack exchange,提问作者Akinod
相关产品推荐
相关产品推荐

