如何在 React Native 的平面列表中更改所选项目的颜色?

Posted

技术标签:

【中文标题】如何在 React Native 的平面列表中更改所选项目的颜色?【英文标题】:How can I change the color of selected item in flatlist in React Native? 【发布时间】:2021-12-24 21:00:14 【问题描述】:

我是 React Native 的新手。字母位于应用程序屏幕的顶部。单击任何字母时,单击的字母会出现在屏幕上。我希望单击字母的颜色与平面列表中其他字母的颜色不同。我该怎么做?

代码:

import React,  useState  from 'react'
import  FlatList, StyleSheet, Text, TouchableOpacity, View  from 'react-native'

const WordPage = () => 

    const [selectedLetter, setSelectedLetter] = useState("A")

    const alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
        "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]

    const _renderAlphabet = ( item ) => 
        return (
            <TouchableOpacity onPress=() =>  setSelectedLetter(item) >
                <View style=styles.alphabetContainer>
                    <Text style=styles.alphabetText>item</Text>
                </View>
            </TouchableOpacity>
        )
    

    return (
        <View style=styles.container>
            <View>
                <FlatList
                    data=alphabet
                    renderItem=_renderAlphabet
                    horizontal
                />
            </View>
            <Text style=styles.text>selectedLetter</Text>
        </View>
    )


export default WordPage

const styles = StyleSheet.create(
    container: 
        flex: 1,
    ,
    alphabetContainer: 
        width: 24,
        height: 24,
        marginLeft: 14,
        marginTop: 14,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'green'
    ,
    alphabetText: 
        fontSize: 18,
        color: 'white',
    ,
    text: 
        fontSize: 100,
        justifyContent: 'center',
        alignSelf: 'center'
    
);

【问题讨论】:

【参考方案1】:

您可以为所选项目创建自定义样式并有条件地应用它。

const _renderAlphabet = ( item ) => 
    return (
        <TouchableOpacity onPress=() =>  setSelectedLetter(item) >
            <View style=item === selectedLetter ? styles.alphabetContainerSelected: styles.alphabetContainer>
                <Text style=styles.alphabetText>item</Text>
            </View>
        </TouchableOpacity>
    )


const styles = StyleSheet.create(
    ...
    alphabetContainer: 
        width: 24,
        height: 24,
        marginLeft: 14,
        marginTop: 14,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'green'
    ,
    alphabetContainerSelected: 
        width: 24,
        height: 24,
        marginLeft: 14,
        marginTop: 14,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'red'
    ,
    ...
);

【讨论】:

以上是关于如何在 React Native 的平面列表中更改所选项目的颜色?的主要内容,如果未能解决你的问题,请参考以下文章

如何在平面列表中交替颜色(React Native)

React-native:如何在触摸时突出显示平面列表项

React Native - 水平平面列表内的水平平面列表

如何在 React Native 的平面列表中的可触摸不透明度内执行函数?

在 React Native 中使用平面列表数据导航

React-Native 嵌套平面列表