You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 21:30:04