노쇼핑 앱 마이너 업데이트 중에서 앱 화면에 배너를 다는 요구사항이 들어왔었다.
맨 위인 탭 바와 필터를 적용하는 곳 아래에 배너를 위치시켜야했고 홈 화면에서 스크롤을 올릴 시, 배너는 사라지게 만들어야하는 작업이다.
React-native에서 배너를 만들 때 swiper를 이용해서 만든다고 하여 swiper로 배너를 만들거다
npm install react-native-swiper
먼저 위 명령어로 swiper부터 추가를 해주자
다음으로는 배너 아이템과 배너 props를 구성합니다
interface BannerItem {
id: string
image: any
title?: string
link?: string
}
interface BannerProps {
items: BannerItem[]
autoplay?: boolean
showPagination?: boolean
loop?: boolean
autoplayTimeout?: number
onPressBanner?: (item: BannerItem) => void
imageStyle?: object
}
banneritem은 배너를 구성하고 있는 것들을 정해주면 됩니다!
배너를 눌렀을 때 설정해둔 링크로 이동시키기 위해 handlePress를 만들고 swiper에 넣어보겠습니다
const handlePress = (item: BannerItem) => {
if (onPressBanner) {
onPressBanner(item)
} else if (item.link) {
Linking.openURL(item.link).catch((err) => {
console.error("링크를 여는데 실패했습니다:", err)
})
}
}
~~~~
<Swiper
className="h-full"
showsPagination={false}
autoplay={autoplay}
loop={loop}
autoplayTimeout={autoplayTimeout}
scrollEnabled={true}
automaticallyAdjustContentInsets={false}
showsHorizontalScrollIndicator={false}
loadMinimal={true}
loadMinimalSize={1}
horizontal={true}
pagingEnabled={true}
>
{items.map((item) => (
<TouchableOpacity
key={item.id}
onPress={() => handlePress(item)}
activeOpacity={0.9}
style={{ flex: 1 }}
>
<Image
source={typeof item.image === "string" ? { uri: item.image } : item.image}
style={[
{
width: screenWidth,
height: "100%",
},
imageStyle,
]}
resizeMode="contain"
/>
</TouchableOpacity>
이렇게하면 배너에 있는 아이템을 터치했을 시 넣어둔 url링크로 이동하게 됩니다!
배너를 보여줄 스크린 화면에 배너 아이템을 만들어 줍니다.
const bannerItems = [
{
id: "1",
image: image,
link: "link",
},
{
id: "2",
image: image2,
link: "link",
},
]
그리고 이제 스크롤할 때 배너만 사라지게 해야하기 때문에 리스트 뷰에 ListHeaderComponent로 넣어주면 됩니다!
<ListView
ref={listViewRef}
data={articles.slice()}
refreshing={refreshing}
estimatedItemSize={177}
onRefresh={() =>
refresh({
detail_category: selectedTab,
sort_by: selectedSort.value,
page: 1,
should_replace: true,
})
}
onEndReached={handleLoadMore}
onEndReachedThreshold={0.5}
ListHeaderComponent={() => (
<Banner items={bannerItems} autoplay={true} autoplayTimeout={4} loop={true} />
)}
