결과
서론
처음엔 React-Native 피커 중 가장 유명한 react-native-picker 라이브러리를 사용했다.
iOS에선 그나마 이쁘게 출력되었는데, Android는 전혀 다른 창으로 보여서 직접 만들기로 했다.
자료가 많지 않아서 애를 먹었다. 나와 같은 사람이 있으리라 생각하고 정리해볼 생각이다.
RN을 시작한 지 얼마 되지 않아 미흡하니 코드는 참고만 해주시면 감사하겠습니다🙏
본론
- 사용 스택
- RN
- StyledComponents
- TypeScript
- 필요한 기능
- Scroll 시 버튼 값 (ex 오전, 오후)이 칸에 고정되도록 출력되어야 한다.
- 가운데에 위치한 버튼 값이 어떤 값인지 알아야 한다.
- 분이 55에서 다음으로 넘어가면 0으로 변경되고 시간이 변해야 한다. (구현 X)
Scroll 시 버튼 값 고정되도록 출력
머리로는 어떻게 해야 할지 감이 잡히는데, 코드로 어떻게 해야 할지 막막했던 것 같다.
말로 요약하자면, Scroll Event에서 contentOffset.y / {Item Height}를사용하여 아이템에 따른 값을 가져왔다.
그 뒤에 useRef로 ScrollView의 y 값을 이동시켜 주었다.
아래는 minute의 예시이다.
const minute = [' ', 0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, ' '];
// 가운대에 출력을 위해 처음과 끝에 빈 배열 추가
const [currentMinute, setCurrentMinute] = useState(0);
const refMinute = useRef(null);
//...중략
const handleMinuteOnScroll = (e: NativeSyntheticEvent<NativeScrollEvent>) => {
const nextCurrent: number = Math.round(e.nativeEvent.contentOffset.y / BUTTON_HEIGHT);
if (nextCurrent < 0) {
return;
}
setCurrentMinute(nextCurrent);
refMinute.current.scrollTo({y: nextCurrent * BUTTON_HEIGHT, animated: true});
};
<ScrollView
ref={refMinute}
showsVerticalScrollIndicator={false}
onScrollEndDrag={handleMinuteOnScroll}
scrollEventThrottle={0}
decelerationRate={'fast'}
>
...
</ScrollView>
사용자가 선택한 값 불러오기
위에서 설명했듯이 [ Scroll Event에서 contentOffset.y / {Item Height}를사용하여 아이템에 따른 값을 가져왔다. ]
이 말은 분(Minute)으로 예를 들면 칸이 변함에 따라 아래와 같이 출력된다. (단 Math 함수를 통해 올림, 반올림, 내림을 했을 때)
빈칸 0
5 1
10 2
15 3
..
그렇다. 그냥 nextCurrent 값에 * 5를 해주면 끝난다. ( 오전, 오후는 함수를 만들어서 변환해 주었다.)
결론 및 느낀 점
머리로는 이래 이래 해서 하면 되겠다! 라고 떠오르는데 아직 코딩 실력이 못 따라가는 게 아쉽다.
라이브러리는 개발자로 지내면서 뗄 수 없을뿐더러 개발 시간 또한 단축시켜준다고 생각한다.
하지만 라이브러리 틀 안에 갇혀서 제한된 기능을 사용 하기보단,
필요할 때 직접 만들어서 사용할 수 있는 개발자가 되고자 노력 중이다.물론 업무였지만..
참고 자료
https://reactnative.dev/docs/scrollview
ScrollView · React Native
Component that wraps platform ScrollView while providing integration with touch locking "responder" system.
reactnative.dev
https://infinitbility.com/react-native-scrollview-scroll-to-position
React native ScrollView scroll to position
The simplest way of scroll to position in react native using ScrollView ref.
infinitbility.com
https://velog.io/@bang9dev/React-Native-Scrollable-Time-Picker-%EB%A7%8C%EB%93%A4%EA%B8%B01
[React-Native] Scrollable Time Picker 만들기(1)
스크롤 가능한 time picker 만들기
velog.io
3월 인턴일지 (3) 📝 : [React-Native] ScrollView로 간단한 carousel 구현하기!
React-Native에서는 다음과 같이 ScrollView로 슬라이더를 구현할 수 있다. 👍 Markup Animated.ScrollView를 사용한다. import 구문: import Animated from 'react-native-reanimated';
velog.io
https://stackoverflow.com/questions/59677122/how-to-get-scrollview-index
How to get scrollview index
I am using react-native scrollview to slide my imageBackground. I am using pagingEnabled to swipe the images. But is there a way I could get number of the index when ever I swipe? I am using the
stackoverflow.com