1. 단일 선택 Single-select flatlist
// 단일 선택
// 상단 state
const [selected, setSelected] = React.useState(new Map());
// data
const Data = [
{
id: '0',
title: 'title1',
},
{
id: '1',
title: 'title2',
},
{
id: '2',
title: 'title3',
},
];
// select 되었을 때의 event
const onSelect = (id, title) => {
setSelected(id);
};
// 렌더 될 Item
const Item = ({id, title, selected, onSelect}) => {
return (
<TouchableOpacity
onPress={() => onSelect(id, title)}
style={{backgroundColor: selected ? '#f00' : '#000'}}>
<Text>
{title}
</Text>
</TouchableOpacity>
);
};
// return 안에 넣을 flatlist
<FlatList
data={Data}
renderItem={({item}) => (
<Item
id={item.id}
title={item.title}
selected={item.id === selected}
onSelect={onSelect}
/>
)}
keyExtractor={(item) => item.id}
extraData={selected}
/>
2. 다중 선택 Multi-select flatlist
// 다중 선택 useCallback 선언 먼저 해야함
// 상단 state
const [selected, setSelected] = React.useState(new Map());
// data
const Data = [
{
id: '0',
title: 'title1',
},
{
id: '1',
title: 'title2',
},
{
id: '2',
title: 'title3',
},
];
// select 되었을 때의 event
const onSelect = useCallback(
(id) => {
const newSelected = new Map(selected);
newSelected.set(id, !selected.get(id));
setSelected(newSelected);
},
[selected],
);
// 렌더 될 Item
const Item = ({id, title, selected, onSelect}) => {
return (
<TouchableOpacity
onPress={() => onSelect(id, title)}
style={{backgroundColor: selected ? '#f00' : '#000'}}>
<Text>
{title}
</Text>
</TouchableOpacity>
);
};
// return 안에 넣을 flatlist
<FlatList
data={Data}
renderItem={({ item }) => (
<Item
id={item.id}
title={item.title}
selected={!!selected.get(item.id)}
onSelect={onSelect}
/>
)}
keyExtractor={item => item.id}
extraData={selected}
/>
시간 낭비 방지용^^......
'Programming > React Native' 카테고리의 다른 글
[React Native] iOS, Android App icon 적용하기 (0) | 2021.01.20 |
---|