Reputation: 87
I have a Flatlist inside my default component, I want to perform an on item click with Touchables, when the item is touched it should get one of its items called "Source" and pass it to another function called "deleteImage". Now the problem is that my RenderItem (Which is called ItemAdImages) is outside the main component but the deleteImage is inside the component so it can't pass "Source" to deleteImage. my renderItem Code:
Export Default Class ... Extends Component{
render(){
return(
<SafeAreaView style={{
marginBottom: 10, flex: 1,
alignContent: 'center'
}}>
<FlatList
data={this.state.avatarsArray}
renderItem={({item}) => <ItemAdImages
source={item.source}
data={item.data}
/>}
numColumns={3}
keyExtractor={(item) => item.data}
contentContainerStyle={{margin: 0}}
extraData={this.state.itemImagesListRefresh}
/>
</SafeAreaView>
)//return
}//render
deleteImage(imageSource){
console.log("image source is = " + imageSource)
for(let i = 0; i < this.state.avatarsArray.length; i++){
if (this.state.avatarsArray[i]['source'] === imageSource){
this.state.avatarsArray.splice(i, 1);
this.setState({itemImagesListRefresh: !this.state.itemImagesListRefresh})
console.log(this.state.avatarsArray)
}
else {
console.log(this.state.avatarsArray[i] + " Not It")
}
}
}//deleteImage
}//main component
and my renderItem function outside main component:
function ItemAdImages({source, data, id, state}) {
return (
<Container style={{height: 45, width: 90, backgroundColor: '#EEEEEE',
margin: 10}}>
<Content>
<TouchableOpacity onPress={() => this.deleteImage(source)}>
<View >
<Image
//source= {{uri: "content://media/external/images/media/29"}}
source= {{uri: source}}
//source= {{uri : this.state.avatarsArray[0].source}}
//source= {{uri : this.state.avatarsArray[0].source}}
style={{width: 90, height: 45,
backgroundColor: '#FF9900'}} />
</View>
</TouchableOpacity>
</Content>
</Container>
) }
The error is :
Upvotes: 0
Views: 535
Reputation: 16334
You should pass the deleteimage function as a parameter to the item component
renderItem={({item}) => <ItemAdImages
source={item.source}
data={item.data}
deleteImage={this.deleteImage}
/>}
And access it just like any other prop
function ItemAdImages({source, data, id, state, deleteImage}) {
return (
<Container style={{height: 45, width: 90, backgroundColor: '#EEEEEE',
margin: 10}}>
<Content>
<TouchableOpacity onPress={() => deleteImage(source)}>
<View >
<Image
//source= {{uri: "content://media/external/images/media/29"}}
source= {{uri: source}}
//source= {{uri : this.state.avatarsArray[0].source}}
//source= {{uri : this.state.avatarsArray[0].source}}
style={{width: 90, height: 45,
backgroundColor: '#FF9900'}} />
</View>
</TouchableOpacity>
</Content>
</Container>
) }
Upvotes: 2