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

How can I add unique keys to <TouchableOpacity> components in React Native?

我正在尝试为我想传递给 onPress 的一些 <TouchableOpacity> 组件生成唯一键,但它没有获取 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>
)}

有时当我的数据没有唯一 ID 时,我会使用这种方法与 lodash

 import { map, uniqueId } from 'lodash'

 {map(someArray, () => (
        <React.Fragment key={uniqueId()}>
          <TextButton />
        </React.Fragment>
      ))}