当项目是地图时获取键和项目 onPress TouchableOpacity

Get key and item onPress TouchableOpacity when items are map

在下面的代码项中正确呈现并工作
但是当我按下 TouchableOpacity 它时 returns 事件。
我使用了 JSON.stringify(event.nativeEvent) 但没有用

我想获取设置在 TouchableOpacity 上的 键值 和该项目数据。

export default class MyLanguages extends Component {
    constructor(props) {
      super(props);
      this.state = {
        languageData: ["English","Hindi","Tamil","Telugu","Gujarati","Marathi","Panjabi"],
      };
    }
    render() {
        return (
            <View style={styles.container}>
                {this.state.languageData.map( (item,index) => {
                    return (
                        <TouchableOpacity key={index}
                            onPress={ (event)=>{
                                alert(event.nativeEvent)
                            }}>
                            <Text style={MyStyle.appFontStyle2}>{item}</Text>
                        </TouchableOpacity>
                    )}
                )}
            </View>
        )
    }
}

itemindex还在onPress回调范围内,可以直接参考:

{this.state.languageData.map((item, index) => {
  return (
    <TouchableOpacity
      key={index}
      onPress={event => {
        alert(`${index}: ${item}`);
      }}
    >
      <Text style={MyStyle.appFontStyle2}>{item}</Text>
    </TouchableOpacity>
  );
)}

您也可以为此使用柯里化函数:

export default class MyLanguages extends Component {
    constructor(props) {
      super(props);
      this.state = {
        languageData: ["English","Hindi","Tamil","Telugu","Gujarati","Marathi","Panjabi"],
      };
    }

   // Curried function (A function which, when invoked (with an argument), returns another function that depends on the argument
   onPressHandler = key => event => {
      console.log(key, event)
   }

    render() {
        return (
            <View style={styles.container}>
                {this.state.languageData.map( (item,index) => {

                    // Invoke the curried function with the index as the argument for the key paremeter,
                    // which returns another function which is set as the onPress event handler
                    return (
                        <TouchableOpacity
                            key={index}
                            onPress = {this.onPressHandler(index)}
                        >
                            <Text style={MyStyle.appFontStyle2}>{item}</Text>
                        </TouchableOpacity>
                    )}
                )}
            </View>
        )
    }
}