使用GlideJS时出现TypeError: default is not a constructor错误的原因
React中使用GlideJS v3触发TypeError: default is not a constructor的解决办法
核心问题:导入方式错误
GlideJS v3采用命名导出而非默认导出,你当前用import Glide from "@glidejs/glide"的默认导入方式,拿到的Glide并不是构造函数,所以调用new Glide()时会报错。
修正导入代码
把导入语句改成命名导入:
import { Glide } from "@glidejs/glide";
额外优化(避免其他潜在问题)
- 不要用setTimeout等待DOM挂载
React中可以用useRef直接绑定DOM元素,确保实例化时元素已经存在,比定时器更可靠:
import { useRef, useMemo, useEffect } from 'react'; import { Glide } from "@glidejs/glide"; const SectionSlider = () => { const sliderRef = useRef(null); // 假设itemPerRow是传入的props或定义的变量 const itemPerRow = 4; const MY_GLIDEJS = useMemo(() => { // 确保DOM元素存在再创建实例 if (!sliderRef.current) return null; return new Glide(sliderRef.current, { perView: itemPerRow, gap: 32, bound: true, breakpoints: { 1280: { perView: itemPerRow - 1 }, 1024: { gap: 20, perView: itemPerRow - 1 }, 768: { gap: 20, perView: itemPerRow - 2 }, 640: { gap: 20, perView: itemPerRow - 3 }, 500: { gap: 20, perView: 1.3 }, }, }); }, [itemPerRow]); // 依赖项是itemPerRow,而非固定的UNIQUE_CLASS useEffect(() => { if (!MY_GLIDEJS) return; MY_GLIDEJS.mount(); // 组件卸载时销毁实例,防止内存泄漏 return () => { MY_GLIDEJS.destroy(); }; }, [MY_GLIDEJS]); return ( <div ref={sliderRef} className="flow-root"> {/* 滑块内容 */} </div> ); };
- 修正useMemo依赖项
你的UNIQUE_CLASS是固定字符串,不需要加入useMemo的依赖数组;真正需要依赖的是itemPerRow,因为配置项里用到了这个变量。
版本验证
你的@glidejs/glide和@types/glidejs__glide版本都是3.6.0,版本匹配正常,无需调整。
内容的提问来源于stack exchange,提问作者dearn44
相关产品推荐
相关产品推荐

