JSX中如何仅给.map遍历数组的id=0元素添加href超链接
实现思路
只需要在遍历projects数组时增加id判断逻辑,仅对id=0的元素用<Link>组件包裹需要跳转的区域,其余元素直接渲染对应内容即可。
代码修改示例
const Projects = () => ( <Section nopadding id="projects"> <SectionDivider /> <SectionTitle main>Projects</SectionTitle> <GridContainer> {projects.map(({ id, image, title, description, tags, source, visit }) => { // 抽离公共的标题区域代码,避免重复书写 const TitleArea = ( <TitleContent> <HeaderThree title>{title}</HeaderThree> <Hr /> </TitleContent> ) return ( <BlogCard key={id}> <Img src={image} /> {/* 仅id为0的元素添加超链接 */} {id === 0 ? <Link href="/campaigns">{TitleArea}</Link> : TitleArea} {/* 此处保留你原有剩余的业务代码 */} </BlogCard> ) })} </GridContainer> </Section> );
注意事项
- 如果需要让整个卡片可点击,只需要调整
<Link>的包裹范围到整个<BlogCard>的内部内容即可,判断逻辑保持不变 - 如果你的项目使用的UI库的
<Link>组件支持disabled属性,也可以直接写成<Link href="/campaigns" disabled={id !== 0}>,不需要做条件渲染,不过需要确认该组件禁用后不会生成可点击的a标签,避免不必要的语义问题
内容的提问来源于stack exchange,提问作者Miller42
相关产品推荐
相关产品推荐

