React Owl Carousel

1
npm install --save react-owl-carousel 

在vite.config.js新增

  • import inject from '@rollup/plugin-inject'
  • inject({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery', }),
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { defineConfig } from 'vite'
import inject from '@rollup/plugin-inject'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
plugins: [
react(),
inject({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
}),
]
})

vite 發生錯誤訊息如圖 安裝
1
npm install @rollup/plugin-inject --save

在使用的組件或是頁面載入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { useEffect, useState } from "react"
import $ from 'jquery';
import OwlCarousel from "react-owl-carousel";
import "owl.carousel/dist/assets/owl.carousel.css";
import "owl.carousel/dist/assets/owl.theme.default.css";

const App = () =>{
const [banners, setBanners] = useState([]);
const api = "https://xxx/api/banners";
const getBanners = () => {
fetch(api, { method: "GET" })
.then((res) => res.json())
.then((data) => {
setBanners(data);
})
.catch((err) => {
console.log(err);
});
};

useEffect(() => {
getBanners();
}, []);
return (
<div>
<OwlCarousel className='owl-theme' loop items={1} autoplay={true} nav>
{banners.map(item => (
<div className="item" key={item._id}>
<img src={item.image} />
<div>{item.subject}</div>
</div>
))}
</OwlCarousel>
</div>
)
}

export default App