-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflastList-scrollTop
More file actions
123 lines (114 loc) · 3.28 KB
/
flastList-scrollTop
File metadata and controls
123 lines (114 loc) · 3.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
import {
View,
Text,
FlatList,
SafeAreaView,
StyleSheet,
ActivityIndicator,
TouchableOpacity,
Image,
} from 'react-native';
import React, { useState, useEffect } from 'react';
const App = () => {
const [isLoading, setIsLoading] = useState(true);
const [data, setData] = useState([]);
const [currentIndex, setCurrentIndex] = useState();
const [refFlatList, setRefFlatList] = useState();
useEffect(() => {
getListPhotos();
return () => {};
}, []);
getListPhotos = () => {
const apiURL = 'https://jsonplaceholder.typicode.com/photos?_limit=20&_page=1';
fetch(apiURL)
.then((res) => res.json())
.then((resJson) => {
setData(resJson);
})
.catch((err) => {
console.log('Error: ', err);
})
.finally(() => setIsLoading(false));
};
const onClickItem = (item, index) => {
setCurrentIndex(index);
const newArrData = data.map((e, index) => {
if (item.id == e.id) {
return {
...e,
seleted: true,
};
}
return {
...e,
seleted: false,
};
});
setData(newArrData);
};
renderItem = ({ item, index }) => {
return (
<TouchableOpacity
onPress={() => onClickItem(item, index)}
style={[
styles.item,
{
// marginTop: 11,
marginLeft: 14,
height: 150,
width: 200,
backgroundColor: item.seleted ? 'orange' : 'white',
},
]}
>
<Image resizeMode="contain" source={{ uri: item.url }} style={{ height: 100, width: 100 }} />
</TouchableOpacity>
);
};
onScroolToItemSelected = () => {
refFlatList.scrollToIndex({ animated: true, index: currentIndex });
};
getItemLayout = (data, index) => {
return { length: 214, offset: 214 * index, index };
};
return (
<SafeAreaView style={styles.container}>
{isLoading ? (
<ActivityIndicator />
) : (
<FlatList
data={data}
renderItem={renderItem}
keyExtractor={(item) => `key-${item.key}`}
getItemLayout={getItemLayout}
ref={(ref) => setRefFlatList(ref)}
horizontal
/>
)}
<TouchableOpacity style={styles.wrapButton} onPress={onScroolToItemSelected}>
<Text style={styles.tex}>Scroll to item selected</Text>
</TouchableOpacity>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
wrapButton: {
alignItems: 'center',
marginHorizontal: 50,
padding: 20,
backgroundColor: 'orange',
},
tex: {
fontSize: 20,
},
item: {
borderWidth: 0.5,
padding: 8,
borderRadius: 10,
justifyContent: 'center',
},
});
export default App;