React Swiper自定义前后切换按钮失效问题求助
React Swiper自定义导航按钮无响应的修复方案
问题原因
初始化Swiper组件时,自定义导航按钮的DOM节点尚未完成渲染,此时nextRef.current和preRef.current的值为null,导致Navigation模块无法绑定点击事件到按钮上。
修复方法
方法一:利用onSwiper回调初始化导航
在Swiper实例创建完成后(此时DOM已挂载,ref能获取到元素),手动设置导航元素并重新初始化Navigation模块:
import React, { useRef } from "react"; import styles from "./food.module.css"; import { Swiper, SwiperSlide } from "swiper/react"; import { Navigation } from "swiper"; import "swiper/css"; import "swiper/css/pagination"; import "swiper/css/navigation"; const Food = () => { const nextRef = useRef(); const preRef = useRef(); const swiperRef = useRef(); return ( <div className={styles.container}> <Swiper slidesPerView={5} spaceBetween={30} slidesPerGroup={5} loop={true} loopFillGroupWithBlank={true} pagination={{ clickable: true, }} modules={[Navigation]} className="mySwiper" onSwiper={(swiper) => { swiperRef.current = swiper; // 绑定导航元素 swiper.navigation.nextEl = nextRef.current; swiper.navigation.prevEl = preRef.current; // 重新初始化导航模块 swiper.navigation.init(); }} > <SwiperSlide> <p className={styles.p}>hello</p> </SwiperSlide> <SwiperSlide> <p className={styles.p}>hello</p> </SwiperSlide> <SwiperSlide> <p className={styles.p}>hello</p> </SwiperSlide> <SwiperSlide> <p className={styles.p}>hello</p> </SwiperSlide> <SwiperSlide> <p className={styles.p}>hello</p> </SwiperSlide> </Swiper> <div ref={preRef}>previous</div> <div ref={nextRef}>next</div> </div> ); }; export default Food;
方法二:使用useEffect延迟绑定导航
利用React的useEffect钩子,在组件挂载完成后再设置导航元素:
import React, { useRef, useEffect } from "react"; import styles from "./food.module.css"; import { Swiper, SwiperSlide } from "swiper/react"; import { Navigation } from "swiper"; import "swiper/css"; import "swiper/css/pagination"; import "swiper/css/navigation"; const Food = () => { const nextRef = useRef(); const preRef = useRef(); const swiperRef = useRef(); useEffect(() => { if (swiperRef.current && nextRef.current && preRef.current) { swiperRef.current.navigation.nextEl = nextRef.current; swiperRef.current.navigation.prevEl = preRef.current; swiperRef.current.navigation.init(); } }, []); return ( <div className={styles.container}> <Swiper slidesPerView={5} spaceBetween={30} slidesPerGroup={5} loop={true} loopFillGroupWithBlank={true} pagination={{ clickable: true, }} modules={[Navigation]} className="mySwiper" onSwiper={(swiper) => (swiperRef.current = swiper)} > <SwiperSlide> <p className={styles.p}>hello</p> </SwiperSlide> <SwiperSlide> <p className={styles.p}>hello</p> </SwiperSlide> <SwiperSlide> <p className={styles.p}>hello</p> </SwiperSlide> <SwiperSlide> <p className={styles.p}>hello</p> </SwiperSlide> <SwiperSlide> <p className={styles.p}>hello</p> </SwiperSlide> </Swiper> <div ref={preRef}>previous</div> <div ref={nextRef}>next</div> </div> ); }; export default Food;
补充说明
两种方法的核心都是确保在DOM节点挂载完成后,再将导航元素绑定到Swiper实例上,这样Navigation模块才能正确找到按钮并添加点击事件。
内容的提问来源于stack exchange,提问作者ali pasha
相关产品推荐
相关产品推荐

