2

我正在尝试在本机反应中检索 FlatList 上单击元素的索引。正如文档所说,我将索引传递给 renderItem 道具。我的代码如下:

/**
 * Goes to the show view of a container
 * @param {*} index 
 */
showContainer = (index) => {
    console.log(index); 
}

render() {
    return (
        <DefaultScrollView style={styles.container}>
            <FlatList
                data={this.props.containers}
                renderItem={(data, index) => (
                    <ListItem
                        containerStyle={{borderBottomWidth: 1, borderBottomColor: "#000"}}
                        key={data.item.id}
                        leftAvatar={Image}
                        onPress={() => {this.showContainer(index)}}
                        rightIcon={{ name: "ios-eye", type: "ionicon" }}
                        subtitle={
                            `${data.item.dummy === true? 'Por favor configura tu dispositivo' : 'Contenido actual: '}`
                        }
                        subtitleStyle={(data.item.dummy == true)? [styles.configurationText, styles.subtitule] : styles.subtitule}
                        title={data.item.name}
                        titleStyle={styles.title}
                    />
                )}/>
        </DefaultScrollView>
    );
}

它起作用的唯一方法是如果我将一个数字作为索引传递,例如: renderItem={(data, index = 0),但是如何传递索引变量以始终具有正确的索引?

提前致谢

4

3 回答 3

7

在将数据传递renderItem.

所以改变:

 renderItem={(data, index) => ( ...

到:

 renderItem={({item, index}) => (...

然后您可以使用item.id例如访问您的数据。

简化的工作演示:

https://snack.expo.io/B1AONkehN

于 2019-05-08T05:11:22.247 回答
1

只需将每一个换data, index{}并更改dataitem,

  renderItem={({item, index}) => ( ....
              ....
              key={item.item.id} // like this every where
于 2019-05-08T05:09:58.710 回答
1

代码中的问题是:

您的代码:

   renderItem={(data, index) => ( 

正确一:

 renderItem={({ item, index }) => (

您可以更新您的 renderItem ,它将解决您的问题。:

renderItem={({ item, index }) => (
           <ListItem
                        containerStyle={{borderBottomWidth: 1, borderBottomColor: "#000"}}
                        key={data.item.id}
                        leftAvatar={Image}
                        onPress={() => {this.showContainer(index)}}
                        rightIcon={{ name: "ios-eye", type: "ionicon" }}
                        subtitle={
                            `${data.item.dummy === true? 'Por favor configura tu dispositivo' : 'Contenido actual: '}`
                        }
                        subtitleStyle={(data.item.dummy == true)? [styles.configurationText, styles.subtitule] : styles.subtitule}
                        title={data.item.name}
                        titleStyle={styles.title}
                    />
        )}
于 2019-05-08T05:10:43.517 回答