5

在下面的代码中,项目被正确呈现并且工作
但是当我按下TouchableOpacity它返回事件。
我使用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>
        )
    }
}
4

2 回答 2

6

item并且index还在onPress回调的范围内,所以可以直接引用:

{this.state.languageData.map((item, index) => {
  return (
    <TouchableOpacity
      key={index}
      onPress={event => {
        alert(`${index}: ${item}`);
      }}
    >
      <Text style={MyStyle.appFontStyle2}>{item}</Text>
    </TouchableOpacity>
  );
)}
于 2018-08-03T07:33:30.353 回答
3

您还可以为此使用咖喱函数:

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>
        )
    }
}
于 2019-11-25T08:58:08.627 回答