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

Next.js13 App目录用LightGallery时遇React.useRef不是函数错误

Next.js 13 App目录中使用LightGallery出现React.useRef不是函数的问题

问题描述

我在开发基于Next.js 13的项目,采用新的App目录结构,需要在动态页面中用LightGallery实现灯箱功能。安装包并将代码粘贴到组件后,出现了React.useRef不是函数的错误。我原本以为是App目录的问题,但看到已有其他人成功实现,所以想排查问题所在。

package.json配置

{"private": true,
"homepage": "http://localhost:3000",
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"@heroicons/react": "^2.0.13",
"@next/font": "^13.1.6",
"@nextui-org/react": "^1.0.0-beta.12",
"@supabase/auth-helpers-nextjs": "^0.5.2",
"@supabase/auth-helpers-react": "^0.3.1",
"@supabase/supabase-js": "^2.2.2",
"@types/gtag.js": "^0.0.12",
"axios": "^1.2.2",
"convertkit-react": "^1.5.5",
"cors": "^2.8.5",
"encoding": "^0.1.13",
"express": "^4.18.2",
"lightgallery": "^2.7.1",
"next": "^13.0.1",
"next-share": "^0.19.0",
"nextjs-cors": "^2.1.2",
"prop-types": "^15.8.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-hotjar": "^5.4.1",
"request": "^2.88.2",
"server-only": "^0.0.1"
},
"devDependencies": {
"@types/cors": "^2.8.13",
"@types/node": "18.11.3",
"@types/react": "18.0.21",
"@types/react-dom": "18.0.6",
"autoprefixer": "^10.4.12",
"eslint": "^8.33.0",
"eslint-config-next": "^13.1.6",
"postcss": "^8.4.18",
"tailwindcss": "^3.2.4",
"typescript": "4.9.4"
}
}

错误信息

错误提示:React.useRef不是函数

灯箱所在动态页面代码

import React from "react";
import Image from "next/image";
import LightGallery from 'lightgallery/react';

// import styles
import 'lightgallery/css/lightgallery.css';
import 'lightgallery/css/lg-zoom.css';
import 'lightgallery/css/lg-thumbnail.css';
import lgThumbnail from 'lightgallery/plugins/thumbnail';
import lgZoom from 'lightgallery/plugins/zoom';

...
export default async function HostPage({
...
  return (
    <div>
        <LightGallery
                onInit={() => console.log("initialized")}
                speed={500}
                plugins={[lgThumbnail, lgZoom]}
            >
                    <Image alt="img1" src="public/ac_logo.png" />
                    <Image alt="img2" src="public/ac_logo.png" />
               
            </LightGallery>
    </div>
  );
}

解决方向建议

  • 标记为客户端组件:Next.js 13 App目录下的组件默认是服务器组件,而LightGallery依赖React客户端API(如useRef),必须在文件顶部添加'use client';指令,将组件转为客户端组件。
  • 升级Next.js版本:当前使用的Next.js 13.0.1是早期版本,对App目录的客户端组件支持不完善,建议升级到13.4及以上的稳定版本。
  • 修正图片路径:Next.js的Image组件引用public目录下的资源时,src应写为/ac_logo.png而非public/ac_logo.png,可先尝试替换为普通<img>标签测试是否路径或组件兼容性问题。
  • 重新安装依赖:删除node_modules和package-lock.json后重新执行npm install,解决可能的依赖冲突:
    rm -rf node_modules package-lock.json
    npm install
    
  • 检查重复React实例:运行npm ls react查看是否存在多个React版本实例,若有需清理依赖树中的重复包。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 00:08:01