Reactjs 未定义react本机平面列表项

Reactjs 未定义react本机平面列表项,reactjs,react-native,react-native-flatlist,Reactjs,React Native,React Native Flatlist,我试图使我的平面列表成为一个可重用的组件,但我得到了一个错误 item is not defined. 如何让onpress函数访问可重用组件中的项 代码: 用法: <WebsiteFlatlist data={places} onPress={this._onPress}/> _onPress = async (places) => { console.log(places) }; 在onPress功能中,您应该执行以下操作: onPres

我试图使我的平面列表成为一个可重用的组件,但我得到了一个错误

item is not defined.
如何让onpress函数访问可重用组件中的项

代码:

用法:

<WebsiteFlatlist data={places} onPress={this._onPress}/>

 _onPress = async (places) => {
        console.log(places)
    };  
在onPress功能中,您应该执行以下操作:

onPress={this._onPress}

这样,您就可以将_onPresslocation函数作为回调传递到您的平面列表中。

您应该绑定该项,并直接将函数传递给onPress props

import React, { Component } from 'react';
import { Text, View } from 'react-native';



export const WebsiteFlatlist = (props) => {
    return(
        <FlatList
        data={props.data}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item }) => (
            <TouchableOpacity
                onPress={props.onPress.bind(null, item)}
            >
                <View>
                    <View>
                        <Text>{item.location}</Text>
                    </View>
                </View>
            </TouchableOpacity>
        )}
    />

    )

};
用法:

<WebsiteFlatlist data={places} onPress={this._onPress}/>

 _onPress = async (places) => {
        console.log(places)
    };  

仅在您的应用程序中传递函数引用。而在公共组件中进行一些更改

分离renderItem组件。 使用函数在组件内部渲染。
您没有将项传递给OnPress。这起作用了,为什么绑定上的第一个参数为null?@obumoon for bind方法的第一个参数是为函数提供上下文。在这种情况下,我们不想绑定上下文,这就是为什么它是空的。
<WebsiteFlatlist data={places} onPress={this._onPress}/>

 _onPress = async (places) => {
        console.log(places)
    };  
const renderItem = (item) => {
return (
<TouchableOpacity onPress={()=>props.onPress(item)}>
   <View>
       <View>
           <Text>{item.location}</Text>
       </View>
   </View>
</TouchableOpacity>
)}

<FlatList
   data={props.data}
   keyExtractor={(item, index) => index.toString()}
   renderItem={
       ({ item }) => (this.renderItem(item))
   }
/>