10月 21, 2020 React
### Image slider / Carousels

在網站上很多時都會使用流水式的 Banner 來告訴使用者最近的事情。

![](https://cdn.19site.net/files/c7/fe/c7fe495b-dd20-41f2-85f0-9e57e10d96e2.png 'Image Slider 都概像這樣子')

### 選擇現成的 Library

初時筆者找到了 `react-alice-carousel` 這個套件,好像很簡單易用,所以後快速的試了一下。不過發現有個問題到現時最新的 Version 都好像還沒有修正好,就是在圖片滑動的中途,如果整個 Component 出現 unmount 的情況,就會出現 Error : Updated on unmounted component。

雖然在它們的 github 上好像沒有人 report 過這樣的 issue。不過筆者確實是遇到了,所以還是選擇另家的好了。

### nuka-carousel

這是另一家大神寫出來的 Image slider,使用上也是非常之簡單。  
Github: https://github.com/FormidableLabs/nuka-carousel

下面會簡單記錄一下使用的方法。

### 安裝

可以使用 npm 來安裝。

```sh
$ npm install nuka-carousel
```

### 使用

使用上也是十分之簡單,只要用 Carousel 包住想要用來 Slide 的內容就可以了,高度是自動的,內容可以用 Array 填入就可以。配上 Div 使用 background 來使用就非常得心應手。

```js
import React from 'react';
import Carousel from 'nuka-carousel';

export default class extends React.Component {
	render() {
		return (		
			<Carousel>
				<img src="https://via.placeholder.com/400/ffffff/c0392b/&text=slide1" />
				<img src="https://via.placeholder.com/400/ffffff/c0392b/&text=slide2" />
				<img src="https://via.placeholder.com/400/ffffff/c0392b/&text=slide3" />
				<img src="https://via.placeholder.com/400/ffffff/c0392b/&text=slide4" />
				<img src="https://via.placeholder.com/400/ffffff/c0392b/&text=slide5" />
				<img src="https://via.placeholder.com/400/ffffff/c0392b/&text=slide6" />
			</Carousel>
		);
	}
}
```

送上 div 顯示圖片的咒語:

```js
<div
	style={{
		background: '#FFFFFF url(https://via.placeholder.com/400/ffffff/c0392b/&text=slide1) center center / cover no-repeat',
		height: '0px',
		paddingBottom: '30%'
	}}
/>
```

以下是筆者使用的 Config:

```js
<Carousel 
	autoplay={ true }
	autoplayInterval={ 4000 }
	withoutControls={ false }
	wrapAround={ true }
	speed={ 1000 }
	renderCenterLeftControls={ () => {} }
	renderCenterRightControls={ () => {} }
>
	{items}
</Carousel>
```
過去文章
2025 (9)
4 (5)
3 (1)
2 (3)
2024 (25)
11 (3)
10 (3)
9 (1)
3 (18)
2022 (6)
10 (1)
6 (2)
5 (1)
3 (1)
1 (1)
2021 (21)
11 (7)
7 (1)
6 (2)
5 (2)
4 (6)
3 (2)
2 (1)
2020 (92)
12 (1)
11 (2)
10 (4)
9 (10)
8 (5)
7 (1)
6 (3)
5 (1)
4 (4)
3 (25)
2 (7)
1 (29)
2019 (57)
12 (25)
11 (7)
9 (25)