我正在尝试使我的列表成为可重复使用的组件,但出现错误
item is not defined.
我如何让我的onpress函数可以访问可重用组件中的项目?
代码:
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}
>
<View>
<View>
<Text>{item.location}</Text>
</View>
</View>
</TouchableOpacity>
)}
/>
)
};
用法:
<WebsiteFlatlist data={places} onPress={() =>{this._onPress(item.location)}}/>
_onPress = async (places) => {
console.log(places)
};
答案 0 :(得分:1)
您应绑定项目,并应直接将函数传递给onPress道具。
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)
};
答案 1 :(得分:0)
在您的onPress
函数中,您应该这样做:
onPress={this._onPress}
通过这种方式,您将_onPress(location)
函数作为回调传递给了您的固定列表。
答案 2 :(得分:0)
仅在<WebsiteFlatlist onPress={this._onPress}>
中传递功能参考。在通用组件中进行一些更改。
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))
}
/>