如何在React Native中为<TouchableOpacity>组件添加唯一键?

问题描述

我正在尝试为我想传递的<TouchableOpacity>的某些onPress组件生成唯一键,但是并没有选择key变量。

const options = ["pic1","pic2","pic2"];

export default function ColourScreen() {
    
    const handlePress = (key) => {
       ...do something wity key...
    }

    return (
        
        <View>

            <TouchableOpacity onPress={key => handlePress(key)}>
                <Image
                    style={styles.icon}
                    source={require('../../../assets/icons/icon_1.jpg')}
                />
            </TouchableOpacity>

            <TouchableOpacity onPress={key => handlePress(key)}>
                <Image
                    style={styles.icon}
                    source={require('../../../assets/icons/icon_2.jpg')}
                />
            </TouchableOpacity>

            <TouchableOpacity onPress={key => handlePress(key)}>
                <Image
                    style={styles.icon}
                    source={require('../../../assets/icons/icon_3.jpg')}
                />
            </TouchableOpacity>

        </View>

    )
}

我尝试手动将其设置为:

<TouchableOpacity 
    key = {1}
    onPress={key => handlePress(key)}>
    <Image
        style={styles.icon}
        source={require('../../../assets/icons/icon_1.jpg')}
    />
</TouchableOpacity>

或:

{options.map((option,key) =>
    <TouchableOpacity
        key = {key}
        onPress={() => handlePress(key)}>
    <Image
        style={styles.icon}
        source={require('../../../assets/icons/icon_1.jpg')}
     />
    </TouchableOpacity>,...

)}

但这只会创建多个组件。

我如何成功做到这一点?

解决方法

您可以拿钥匙并将其映射到您的图标。

const icons = [
  require(`../../../assets/icons/icon_1.jpg`),reqiuire(`../../../assets/icons/icon_2.jpg`),require(`../../../assets/icons/icon_3.jpg`),require(`../../../assets/icons/icon_4.jpg`),]

{options.map((option,key) =>
    <TouchableOpacity
        key = {key}
        onPress={() => handlePress(key)}>
    <Image
        style={styles.icon}
        source={icons[key]}
     />
    </TouchableOpacity>
)}