我正在尝试将我的平板列表变成一个可重用的组件,但是我得到了一个错误。
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)
}; 发布于 2019-07-01 05:38:15
您应该绑定该项,并将一个函数直接传递给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)
}; 发布于 2019-07-01 05:20:51
在您的onPress函数中,您应该这样做:
onPress={this._onPress}通过这种方式,您可以将_onPress(location)函数作为回调传递到平面列表。
发布于 2019-07-01 05:40:11
只在<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))
}
/>https://stackoverflow.com/questions/56830275
复制相似问题