분류 Reactjs

react-native-pager

컨텐츠 정보

  • 조회 352 (작성일 )

본문

React Native를 위한 완벽하게 제어 가능한 고성능 pager


https://github.com/CrowdLinker/react-native-pager 


kilter-cards.giftabs-example.gif 



설치 


yarn add @crowdlinker/react-native-pager


엑스포를 사용하는 경우 모든 종속성이 기본적으로 이미 설치되어 있습니다. 그렇지 않은 경우 이 라이브러리와 함께 두 가지 종속성을 설치해야 합니다.

yarn add react-native-gesture-handler
yarn add react-native-reanimated


이를 설정하기 위한 추가 단계가 있습니다.


 


// lots more examples are available in example/src directory of this repo

import React, { useState } from 'react';
import { View } from 'react-native';
import { Pager, PagerProvider } from '@crowdlinker/react-native-pager';
import { Slide } from './shared-components';

function MyPager() {
  const [activeIndex, onChange] = useState(1);

  return (
    <PagerProvider activeIndex={activeIndex} onChange={onChange}>
      <Pager>
        <Slide />
        <Slide />
        <Slide />
        <Slide />
      </Pager>
    </PagerProvider>
  );
}


API Reference 


Pager 


import { Pager } from '@crowdlinker/react-native-pager'

Props
--------
children: React.ReactNode[];
activeIndex?: number; - active screen
onChange?: (nextIndex: number) => void; - active screen changed
initialIndex?: number; - initial active screen
springConfig?: Partial<SpringConfig> - configuration for spring transitions on swipe / snap
pageInterpolation?: iPageInterpolation - see below - configuration for individual page transforms
panProps?: Partial<GestureHandlerProperties> - configuration for <PanGestureHandler />
pageSize?: number; - percentage (0 - 1), how far should it page on index change
threshold?: number; - percentage (0 - 1), how far should the user drag before snapping to next / prev
minIndex?: number; - minimum index to swipe to (default 0)
maxIndex?: number; - maximum index to swipe to (default children.length - 1)
adjacentChildOffset?: number; - the number of children adjacent to the activeIndex to render
style?: ViewStyle; - style for pages
containerStyle?: ViewStyle - style for pan handler container
animatedValue?: Animated.Value<number>; - total translation value of the pager
animatedIndex?: Animated.Value<number>; - activeIndex as an animated value e.g intermediate values
type?: 'horizontal' | 'vertical'; - target horizontal swipes or vertical swipes
clamp?: {
  prev?: number; - percentage (0 - 1) - clamp children to the left of the active screen
  next?: number; - percentage (0 - 1) - clamp children to the right of the active screen
};
clampDrag: {
  prev?: number - max drag distance to previous screen,
  next?: number - max drag distance to next screen
}


이 인터페이스는 위협적으로 보이지만 거의 모든 소품은 선택 사항이며 특정 동작을 사용자 정의합니다. 많은 사용사례에는 필요하지 않습니다.


PagerProvider 


import { PagerProvider } from '@crowdlinker/react-native-pager'

Props
--------
children: React.ReactNode;
initialIndex?: number;
activeIndex?: number;
onChange?: (nextIndex: number) => void;


Pagination 


import { Pagination } from '@crowdlinker/react-native-pager'

Props
--------
children: React.ReactNode;
pageInterpolation: iPageInterpolation;
style?: ViewStyle;


Slider 

import { Slider } from '@crowdlinker/react-native-pager'

Props
--------
numberOfScreens: number;
style: ViewStyle;


Progress 


import { Progress } from '@crowdlinker/react-native-pager'

Props
--------
numberOfScreens: number;
style: ViewStyle;


Hooks 


<PagerProvider />에서 <Pager />를 래핑 할 때 화면에 사용할 수 있는 유용한 후크가 많이 있습니다.


  usePager(): [activeIndex, onChange, translationValue, animatedIndex]
  useFocus(): boolean -> is screen focused
  useOffset(index: number) -> animatedIndex value relative to the given index
  useOnFocus(fn) -> fn() to fire on screen focus
  useIndex() -> the index of the screen
  useAnimatedIndex() -> the animatedIndex value of the pager
  useInterpolation(interpolationConfig) -> interpolated style object


animatedIndex 란 무엇입니까? 


애니메이션 인덱스는 활성 인덱스의 애니메이션 값을 나타내며 가능한 중간 값을 포함합니다. 이동 또는 전환시 activeIndex 값은 0-> 1에서 이동하지만 animatedIndex 값은 이 전환 동안 0과 1 사이의 모든 중간 값을 캡처 합니다.


Hooks in action


function MySlide(props) {
  const [data, setData] = useState();

  useOnFocus(() => {
    if (!data) {
      myApi.fetchData(props);
    }
  });

  const style = useInterpolation({
    transform: [
      {
        scale: {
          inputRange: [-1, 0, 1],
          outputRange: [0.9, 1, 0.9],
          extrapolate: 'clamp',
        },
      },
      {
        rotate: {
          unit: 'deg',
          inputRange: [-1, 0, 1],
          outputRange: [90, 0, 120],
        },
      },
    ],
  });

  return <Animated.View style={{ flex: 1, ...style }}>...</Animated.View>;
}


Interpolation 


이 라이브러리의 핵심 기능 중 하나는 집중된 화면을 기준으로 화면의 위치를 ​​기반으로 스타일 변환을 사용자 정의 할 수 있다는 것입니다.


보간 구성의 예는 다음과 같습니다.


const scaledDown = {
  transform: [
    {
      scaleX: {
        inputRange: [-1, 0, 1],
        outputRange: [0.8, 1, 0.8],
        extrapolate: 'clamp',
      },
    },
  ],
};


객체 자체는 일반적으로 <Animated.View /> 구성 요소에 전달하는 모든 스타일 소품과 모양이 같습니다. 그러나 이러한 속성 값은 보간 구성을 정의합니다.


입력 범위는 초점이 맞춰진 화면과 관련된 위치를 나타냅니다.


inputRange: [-1, 0, 1];
// [-1] targets the screen before the focused screen
// [0] targets the screen that is focused
// [1] targets the screen after the focused screen


출력 범위는 지정된 각 inputRange 값에 적용될 스타일 값을 반영합니다.


outputRange: [0.8, 1, 0.8];
// [0.8] will be applied to the screen before the focused screen
// [1] will be applied to the screen that is focused
// [0.8] will be applied to the screen after the focused screen


이 경우 초점이 맞춰진 화면의 왼쪽과 오른쪽에 있는 화면은 크기의 80 %로 조정되며 이 범위를 벗어난 화면은 80 %로 표시됩니다.


이 구성을 pageInterpolation 소품으로 전달하여 <Pager />에서 모든 화면의 동작을 사용자 정의 할 수 있습니다. 보간은 변환, 회전 등과 같은 모든 종류의 스타일 속성을 대상으로 할 수 있습니다.


또는 useInterpolation() 후크를 사용하여 개별 화면의 스타일을 사용자 정의 할 수 있습니다. 이는 동일한 구성 객체를 허용하며 Animated에 적용 할 수 있는 스타일 속성을 반환합니다.


보간 설정은 React 네이티브 재구성 문서에서 찾을 수 있습니다.


 


위의 gif (및 그 이상)의 모든 예제는 이 repo의 /example/src 디렉토리에서 사용할 수 있습니다. 대부분의 경우 pageInterpolation prop의 구성이 다릅니다. 당신이 이것들로 할 수 있는 모든 종류의 깔끔한 것들이 있습니다-당신이 공유하고 싶은 특정 구성이 있다면, PR을 제출하고 사랑을 전파하십시오!