Take react as an example. The react component is as follows:

1. Initialization

Specific parameters, see: www.xiaoshu168.com/jquery/103….

MySwiper = new Swiper(this.swiperref.current, {loop: Autoplay: {// Slide effect delay: 1500, // slide interval disableOnInteraction: False}, centeredSlides: true, // center display, default left navigation: {// event selector nextEl: '. Swiper-button-next ', // next page prevEl: '. Swiper-button-prev ', // previous page}, pagination: { '.swiper-pagination'}})} destorySwiper = () => {// Destroy if (! this.mySwiper) return if (this.swiperRef.current) { this.mySwiper.destroy(true, true) } }Copy the code

2, the binding

render() { const { data } = this.props return <div> <div ref={this.swiperRef} className="swiper-container"> <div The className = "swiper - wrapper" > {/ / round figure contents (data | | []). The map ((item, index) => <div key={index} className="swiper-slide"> { item.map((cell, key) => <div className="item" key={key}> <div className="item-img"> <img src={cell.img} alt=""/> </div> <div className="item-other"} dangerouslySetInnerHTML={{ __html: cell.name }}></div> </div>)} </div>) } </div> </div> <div className="swiper-pagination"></div> <div className="swiper-button-prev"></div> <div className="swiper-button-next"></div> </div> }Copy the code

3,

componentDidMount() { this.initSwiper() } componentDidUpdate(prevProps) { if (this.props.data ! == prevProps.data) { this.destorySwiper() this.initSwiper() } } componentWillUnmount() { this.destorySwiper() }Copy the code

The class is written as follows:

import { useState, useEffect, useRef } from 'react' export default function ({ data }) { const [mySwiper, setMySwiper] = useState(() => {}) const swiperRef = useRef() useEffect(() => { initSwiper() return () => destorySwiper() // The return function is equivalent to componentWillUnmount} ComponentDidMount useEffect(() => {destorySwiper() initSwiper()}, [data]) UseEffect (() => initSwiper(), []) const initSwiper = () => {// Define setMySwiper(new Swiper(this.swiperref.current, {loop: Autoplay: {// Slide effect delay: 1500, // slide interval disableOnInteraction: False}, centeredSlides: true, // center display, default left navigation: {// event selector nextEl: '. Swiper-button-next ', // next page prevEl: '. Swiper-button-prev ', // previous page}, pagination: { '.swiper-pagination' } })) } const destorySwiper = () => { ... } return <div> <div ref={swiperRef} className="swiper-container"> </div> }Copy the code