FlatList를 사용하여 표시되는 카테고리 목록이 있습니다. 단일 항목 OnPress의 색상을 변경하여 사용자가 선택한 항목에 대한 피드백을 얻었지만 FlatList의 모든 항목이 색상을 변경합니다.
선택한 유일한 항목의 색상이 변경되고 다른 항목이 선택되면 원래 색상으로 돌아가도록 이와 같은 것을 구현하는 방법은 무엇입니까?
다음은 사용 된 코드의 샘플입니다.
import colors from "../config/colors";
function Categories() {
return (
<View style={styles.Categories}>
<FlatList
horizontal
showsHorizontalScrollIndicator={false}
style={{}}
data={category}
keyExtractor={(item) => item.id}
renderItem={({ item }) => {
return <Text style={styles.Text}>{item.title}</Text>;
}}
/>
</View>
);
}
선택한 항목을 로컬 상태로 유지하고 각 항목에 대해 선택한 플래그를 가지고 요구 사항에 따라 스타일을 전환해야합니다.
const styles = StyleSheet.create({
selectedText: {
color: 'blue',
},
normalText: {
color: 'black',
},
});
function Categories(props) {
const [categroy, updateCategory] = React.useState(props.category);
const updateOnPress = (index) => {
const categories = categroy.map((item) => {
item.selected = false;
return item;
});
categories[index].selected = true;
updateCategory(categories);
};
return (
<View style={styles.Categories}>
<FlatList
horizontal
showsHorizontalScrollIndicator={false}
style={{}}
data={categroy}
keyExtractor={(item) => item.id}
renderItem={({ item, index }) => {
return (
<TouchableOpacity onPress={() => updateOnPress(index)}>
<Text
style={item.selected ? styles.selectedText : styles.normalText}>
{item.title}
</Text>
</TouchableOpacity>
);
}}
/>
</View>
);
}
아래와 같은 구성 요소를 사용할 수 있습니다.
< Categories
category={[
{ id: 1, title: 'aa' },
{ id: 2, title: 'bb' },
{ id: 3, title: 'cc' },
]}
/>
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다