๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“ฑ Cross Platform/React Native

[React Native] ์Šค์™€์ดํ”„ ํ•˜๋ฉด ์‚ญ์ œ ๋ฒ„ํŠผ ๋‚˜์˜ค๋Š” ์ปดํฌ๋„ŒํŠธ ๊ตฌํ˜„ํ•˜๊ธฐ (Swipeable Component with delete button)

by Fomagran ๐Ÿ’ป 2022. 8. 18.
728x90
๋ฐ˜์‘ํ˜•

์•ˆ๋…•ํ•˜์„ธ์š” Foma ์ž…๋‹ˆ๋‹ค.

 

์˜ค๋Š˜์€ React-Native์—์„œ ์ปดํฌ๋„ŒํŠธ๋ฅผ ์Šค์™€์ดํ”„ ํ–ˆ์„ ๋•Œ ์‚ญ์ œ ๋ฒ„ํŠผ์ด ๋‚˜์˜ค๋Š” ๊ธฐ๋Šฅ์„ ์ •๋ฆฌํ•ด ๋ณด๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค.

 

๋ฐ”๋กœ ์‹œ์ž‘ํ• ๊ฒŒ์š”~


Preview

 


Install

 

npm install --save react-native-gesture-handler

Screen.tsx

 

import {Swipeable, GestureHandlerRootView} from 'react-native-gesture-handler';

 

์˜ค๋ฅธ์ชฝ์— ๋“ค์–ด๊ฐˆ Delete ๋ฒ„ํŠผ์„ ๋งŒ๋“ค์–ด ์ค๋‹ˆ๋‹ค.

 

dragX๋ฅผ ๋ฐ›์•„์™€ ์• ๋‹ˆ๋ฉ”์ด์…˜์„ ์ ์šฉํ•˜๊ณ , id์— List์˜ index๋ฅผ ๋ฐ›์•„์™€ ๋ฒ„ํŠผ์„ ๋ˆŒ๋ €์„ ๋•Œ ํ•ด๋‹น index๋ฅผ ์ถœ๋ ฅํ•ด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

 

  const renderRightActions = (dragX, index) => {
    const trans = dragX.interpolate({
      inputRange: [0, 50, 100, 101],
      outputRange: [-20, 0, 0, 1],
    });
    return (
      <Pressable onPress={() => console.log(index)}>
        <Animated.Text
          style={[
            styles.delete,
            {
              transform: [{translateX: trans}],
            },
          ]}>
          Delete
        </Animated.Text>
      </Pressable>
    );
  };

 

View

 

์•„๋ž˜์™€ ๊ฐ™์ด GestureHandlerRootView๋กœ ํ•œ๋ฒˆ ๊ฐ์‹ธ์ฃผ๊ณ ,

 

Swipable ์ปดํฌ๋„ŒํŠธ๋กœ ์Šค์™€์ดํ”„๊ฐ€ ๊ฐ€๋Šฅํ•˜๊ฒŒ ํ•  ์ปดํฌ๋„ŒํŠธ๋ฅผ ๊ฐ์‹ธ ์ค๋‹ˆ๋‹ค.

 

renderRightActions: ์ปดํฌ๋„ŒํŠธ๋ฅผ ์Šค์™€์ดํ”„ ํ–ˆ์„ ๋•Œ ์˜ค๋ฅธ์ชฝ ์•ก์…˜์ด ๋‚˜์˜ค๋„๋ก ํ•˜๋Š” ํŒŒ๋ผ๋ฏธํ„ฐ

 

ํ•ด๋‹น ํŒŒ๋ผ๋ฏธํ„ฐ์— ์œ„์—์„œ ๋งŒ๋“ค์–ด ์ค€ renderRightActions๋ฅผ ๋„ฃ์–ด์ฃผ๋Š”๋ฐ, dragX๋Š” ์Šค์™€์ดํ”„(drag) ํ–ˆ์„ ๋•Œ x์˜ ์œ„์น˜์™€ ํ˜„์žฌ ๋ฆฌ์ŠคํŠธ์˜ id๊ฐ’์„ ๋ณด๋‚ด์ค๋‹ˆ๋‹ค.

 

      <FlatList
      	...
        renderItem={({item, index}) => (
          <GestureHandlerRootView>
            <Swipeable
              renderRightActions={dragX => renderRightActions(dragX, index)}>
              <ChatRoomCell chatRoom={item}></ChatRoomCell>
            </Swipeable>
          </GestureHandlerRootView>
        )}
      />

 

Delete ๋ฒ„ํŠผ์„ ๋ˆ„๋ฅด๋ฉด ๋ฆฌ์ŠคํŠธ์˜ ์ธ๋ฑ์Šค๊ฐ€ ์ •์ƒ์ ์œผ๋กœ ์ถœ๋ ฅ๋ฉ๋‹ˆ๋‹ค.

 

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€