在React Native Grid View中添加项目单击事件

时间:2018-07-24 09:13:59

标签: reactjs react-native

请在下面找到我的代码,并帮助我在网格视图中为项目添加项目单击侦听器。请找到我跟随library link的链接。

当用户单击网格列表中的每个项目时,我需要在警报中显示名称。样式未包含在代码中

预先感谢

import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View,
TouchableWithoutFeedback
} from 'react-native';
import GridLayout from 'react-native-layout-grid';

class HomeScreen extends Component {

renderGridItem = (props) => (
<View style={styles.item}  >
  <View style={styles.flex} />
  <Text style={styles.name} >
    {props.name}
  </Text>
</View>
);
render() {
const items = [];
for (let x = 1; x <= 30; x++) {
  items.push({
    name: `Grid ${x}`
  });
}
return (
  <View style={styles.container}>
    <Text style={styles.welcome}>
      Grid Layout
    </Text>
    <View style={styles.flex}>
      <GridLayout
        items={items}
        itemsPerRow={2}
        renderItem={this.renderGridItem}>
      </GridLayout>
    </View>
  </View>
);
}
}


export default HomeScreen;

2 个答案:

答案 0 :(得分:3)

您可以使用可触摸组件之一(反应本机文档)来代替在<View>中使用renderGridItem

例如使用<TouchableOpacity >

renderGridItem = (props) => (
  <TouchableOpacity style={styles.item} onPress={() => this.showAlert(props.name)}>
    <View style={styles.flex} />
    <Text style={styles.name} >
      {props.name}
    </Text>
  </TouchableOpacity>
);

showAlert = (name) => {
   Alert.alert(
    'Alert Title',
    `The user name is: ${name}`,
    [
      {text: 'OK', onPress: () => console.log('OK Pressed')},
    ],
    { cancelable: false }
  )
}

答案 1 :(得分:1)

为什么不将renderGridItem包装在TouchableWithoutFeedback中?

renderGridItem = (props) => (
  <TouchableWithoutFeedback onPress={()=> Alert.alert(props.name)}>
    <View style={styles.item}  >
     <View style={styles.flex} />
       <Text style={styles.name} >
       {props.name}
       </Text>
     </View>
    <TouchableWithoutFeedback />
  );

此外,您还需要从react-native导入Alert。