Flatlist 를 이용하면 배열로 된 데이터를 이용해서 반복적인 뷰를 만들 수 있다.
Flatlist 외부에서 버튼이나 함수를 통해 원하는 아이템이 있는 곳으로 스크롤이 필요할 때가 있다.
상단에 const flatListRef = useRef(); 를 선언하고
Flatlist에 ref={flatListRef}를 추가한다.
초기 이동이 필요할 경우 initialScrollIndex 속성에 번호를 넣어주면 된다.
const flatListRef = useRef();
<FlatList
ref={flatListRef}
initialScrollIndex={1}
data={data}
renderItem={renderItem}
keyExtractor={item => item.key}
/>
useEffect나 함수에서 flatListRef.current.scrollToIndex({animated: true, index: 2}); 이런식으로 index의 값에 이동시키고 싶은 아이템 번호를 넣는다.
하지만 flatListRef.current 가 잡혀있을 때 해야 오류가 나지 않는다.
if(flatListRef.current){
flatListRef.current.scrollToIndex({animated: true,index: 2});
}
이 예제는 함수형 컴포넌트로 작성한 것이다. 클래스형 컴포넌트는 ref나 .current 의 사용법이 좀 다르기 때문에 유의해야 한다.
전체 테스트할 수 있는 코드는 아래와 같다.
(온라인으로 결과 확인하려면 [링크] 클릭)
import React, {useRef, useState, useEffect} from 'react';
import { FlatList, View, Text,Button} from "react-native";
const data = [
{ key: 1, title : "aaa", },
{ key: 2, title : "bbb", },
{ key: 3, title : "ccc", },
{ key: 4, title : "ddd", }
];
const SetCheckBox = () => {
const flatListRef = useRef();
const [selectNumber, setSelectNumber] = useState(0);
const renderItem = ({ item }) => (
<View style={{padding:10,marginBottom:10,backgroundColor:'#eee'}}>
<Text>{item.key} : {item.title}</Text>
</View>
);
useEffect( () => {
if(flatListRef.current){
flatListRef.current.scrollToIndex({animated: true,index:selectNumber});
}
},[selectNumber])
return(
<>
<View style={{ height: 40 }}>
<FlatList
ref={flatListRef}
initialScrollIndex={0}
data={data}
renderItem={renderItem}
keyExtractor={item => item.key}
/>
</View>
<Button
onPress={ () => setSelectNumber(2)}
title="클릭!"
color="#841584"
/>
</>
)
}
export default SetCheckBox;