2023 年 7 月 28 日更新 - 添加虚拟幻灯片实现
让我们仔细了解如何在 React 中使用 Swiper Web 组件。
参数
React 尚未原生支持自定义元素(Web 组件),因此此代码
<swiper-container
slides-per-view={3}
breakpoints={{
768: {
slidesPerView: 4,
},
}}
>
...
</swiper-container>
实际上呈现为以下内容
<swiper-container slides-per-view="3" breakpoints="[object Object]">
...
</swiper-container>
这不是我们期望的。
这就是为什么需要通过传递 参数作为属性 在 React 中使用 Swiper 元素,并使用自定义初始化
import { useEffect, useRef } from 'react';
import { register } from 'swiper/element/bundle';
export default function App() {
const swiperRef = useRef(null);
useEffect(() => {
// Register Swiper web component
register();
// Object with parameters
const params = {
slidesPerView: 3,
breakpoints: {
768: {
slidesPerView: 4,
},
},
};
// Assign it to swiper element
Object.assign(swiperRef.current, params);
// initialize swiper
swiperRef.current.initialize();
}, []);
return (
<swiper-container init="false" ref={swiperRef}>
...
</swiper-container>
);
}
事件
与事件相同,它们不能使用 React 的 on[Event]
语法分配,而应使用 .addEventListener
方法或通过在参数中传递它们来添加
import { useEffect, useRef } from 'react';
import { register } from 'swiper/element/bundle';
export default function App() {
const swiperRef = useRef(null);
useEffect(() => {
// Register Swiper web component
register();
// Add event listener
swiperRef.current.addEventListener('swiperslidechange', (e) => {
console.log(e.detail);
});
// Object with parameters
const params = {
// or pass it in on
on: {
slideChange(s) {
console.log(s);
},
},
};
// Assign it to swiper element
Object.assign(swiperRef.current, params);
// initialize swiper
swiperRef.current.initialize();
}, []);
return (
<swiper-container init="false" ref={swiperRef}>
...
</swiper-container>
);
}
自定义包装组件
如果你的项目中有许多 Swiper,我们可以创建一个简单的 React 组件,它基本上包装一个 Swiper 元素
import { useEffect, useRef } from 'react';
import { register } from 'swiper/element/bundle';
export function Swiper(props) {
const swiperRef = useRef(null);
const {
children,
...rest
} = props;
useEffect(() => {
// Register Swiper web component
register();
// pass component props to parameters
const params = {
...rest
};
// Assign it to swiper element
Object.assign(swiperRef.current, params);
// initialize swiper
swiperRef.current.initialize();
}, []);
return (
<swiper-container init="false" ref={swiperRef}>
{children}
</swiper-container>
);
}
export function SwiperSlide(props) {
const {
children,
...rest
} = props;
return (
<swiper-slide {...rest}>
{children}
</swiper-slide>
);
}
现在,我们可以在我们的应用程序中以以下方式使用它
import { Swiper, SwiperSlide } from 'path/to/my-swiper.jsx';
export default function App() {
return (
<Swiper
slidesPerView={3}
breakpoints={{ 768: { slidesPerView: 4 } }}
on={{
slideChange: () => console.log('slide changed'),
progress: (s, progress) => console.log(`progress is ${progress}`),
}}
>
<SwiperSlide>Slide 1</SwiperSlide>
<SwiperSlide>Slide 2</SwiperSlide>
<SwiperSlide>Slide 3</SwiperSlide>
</Swiper>
);
}
虚拟幻灯片
如果您使用虚拟幻灯片,我们可以更深入地实现 React 方式的虚拟幻灯片。我们需要按以下方式稍微修改 Swiper
组件
import React, { useEffect, useState, useRef } from 'react';
import { register } from 'swiper/element/bundle';
export function Swiper(props) {
const swiperRef = useRef(null);
const {
children,
virtual, // specify virtual prop
...rest
} = props;
// store virtual data
const [virtualData, setVirtualData] = useState({
from: 0,
to: 0,
offset: 0,
slides: [],
});
useEffect(() => {
// Register Swiper web component
register();
// pass component props to parameters
const params = {
...rest
};
// if we have virtual prop passed add virtual prameters
if (virtual) {
params.virtual = {
enabled: true,
// pass component children (slides) in `slides` array
slides: children,
// set virtual data on renderExternal
renderExternal(vd) {
setVirtualData(vd);
},
};
}
// Assign it to swiper element
Object.assign(swiperRef.current, params);
// initialize swiper
swiperRef.current.initialize();
}, []);
// calc slides to render
const slides = virtual
? virtualData.slides.map((slide, index) =>
// clone slide
React.cloneElement(slide, {
// add key
key: virtualData.from + index,
// set slides offset
style: {
[props.direction === "vertical" ? "top" : "left"]:
virtualData.offset,
},
// add and swiper slide index to data attribute
["data-swiper-slide-index"]: virtualData.from + index,
})
)
: children; // return children if virtual is disabled
return (
<swiper-container init="false" ref={swiperRef}>
{slides}
</swiper-container>
);
}
// SwiperSlide component stays the same
export function SwiperSlide(props) {
const {
children,
...rest
} = props;
return (
<swiper-slide {...rest}>
{children}
</swiper-slide>
);
}
现在,我们可以在 React 中轻松创建带有虚拟幻灯片的 Swiper
import { Swiper, SwiperSlide } from 'path/to/my-swiper.jsx';
export default function App() {
return (
<Swiper virtual navigation>
<SwiperSlide>Slide 1</SwiperSlide>
<SwiperSlide>Slide 2</SwiperSlide>
<SwiperSlide>Slide 3</SwiperSlide>
...
<SwiperSlide>Slide 1000</SwiperSlide>
</Swiper>
);
}
P.S.
和往常一样,如果您喜欢 Swiper,请通过捐赠或认捐来支持该项目
- 在 Patreon 上:https://www.patreon.com/swiperjs
- 在 Open Collective 上:https://opencollective.com/swiper
并查看我们的高级项目
您的支持对我们来说意义重大!