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

如何在NextJS前端调用Strapi API多张图片并实现轮播功能

NextJS+Strapi轮播多图加载实现方案

前提确认

Strapi侧的titlePicture字段为多媒体类型,且API请求时已配置populate规则获取完整的图片嵌套数据,请求示例如下:

// getServerSideProps 或 getStaticProps 中请求Strapi API
const res = await fetch(`${process.env.NEXT_PUBLIC_STRAPI_API_URL}/activities?filters[slug][$eq]=${params.slug}&populate=titlePicture`)
const { data } = await res.json()
const activity = data[0]

你现在能正常拿到titlePicture[0]的数据,说明数组结构是正常的,直接遍历数组即可拿到所有图片。

完整实现代码(基于Tailwind + 轻量轮播库react-responsive-carousel)

1. 先安装依赖

npm install react-responsive-carousel

2. [slug].js 页面代码

import { Carousel } from 'react-responsive-carousel';
import "react-responsive-carousel/lib/styles/carousel.min.css"; // 导入轮播默认样式
import Image from 'next/image';

export default function ActivityDetail({ activity }) {
  // 容错处理:图片为空时展示占位
  if (!activity?.titlePicture || activity.titlePicture.length === 0) {
    return <div className="w-full h-96 bg-gray-100 flex items-center justify-center">暂无图片</div>
  }

  return (
    <div className="max-w-4xl mx-auto p-4">
      {/* 轮播组件 */}
      <Carousel 
        showArrows={true}
        infiniteLoop={true}
        showThumbs={false}
        autoPlay={true}
        className="rounded-lg overflow-hidden shadow-lg"
      >
        {/* 遍历所有图片生成轮播项 */}
        {activity.titlePicture.map((picItem, index) => (
          <div key={index} className="relative w-full h-[500px]">
            <Image
              src={`${process.env.NEXT_PUBLIC_STRAPI_API_URL || 'http://localhost:1337'}${picItem.formats.large.url}`}
              alt={picItem.name || `活动图片${index+1}`}
              fill
              className="object-cover"
              priority={index === 0} // 首图优先加载
            />
          </div>
        ))}
      </Carousel>

      {/* 其他页面内容 */}
      <h1 className="text-3xl font-bold mt-6">{activity.title}</h1>
    </div>
  )
}

export async function getServerSideProps({ params }) {
  const { slug } = params;
  // 生产环境建议把接口地址存在环境变量,不要硬写
  const apiUrl = process.env.NEXT_PUBLIC_STRAPI_API_URL || 'http://localhost:1337';
  const res = await fetch(`${apiUrl}/activities?filters[slug][$eq]=${slug}&populate=*`);
  const result = await res.json();
  
  return {
    props: {
      activity: result.data[0] || {}
    }
  }
}

注意事项

  • 生产环境把Strapi接口地址存在NEXT_PUBLIC_STRAPI_API_URL环境变量中,避免硬编码本地地址
  • 如果不用第三方轮播库,也可以自己基于Tailwind + JS实现原生轮播,核心逻辑还是遍历titlePicture数组生成所有轮播项
  • 用到NextJS的Image组件时,需要在next.config.js中配置Strapi的域名作为图片远程地址:
// next.config.js
module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'http',
        hostname: 'localhost',
        port: '1337',
        pathname: '/uploads/**',
      },
    ],
  },
}

参考截图(Strapi titlePicture集合配置)

Strapi中的titlePicture集合

内容的提问来源于stack exchange,提问作者Ibo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 10:15:03