I have a file called home.js
that looks like this:
import React, { useState } from 'react'
import { View, Text, FlatList, Card, TouchableOpacity } from 'react-native'
export const addProject = (flowerbed) => {
flowerbed.key = Math.random().toString()
setFlowerbed((currentFlowerbeds) => {
return [flowerbed, ...currentFlowerbeds]
})
setModalOpen(false)
}
export default function HomeScreen() {
const [flowerbeds, setFlowerbed] = useState(false);
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<FlatList data={flowerbeds} renderItem={({ item }) => (
<TouchableOpacity >
<Card>
<Text>{ item.title }</Text>
</Card>
</TouchableOpacity>
)} />
</View>
)
}
In function addProject
I need to call function setFlowerbed
which is inside HomeScreen
, but I get an error: can't find variable: setFlowerbed . I cannot put function addProject
inside HomeScreen
because I need to access it in another file:
import { addProject } from './screens/home';
Is there a way to fix this error? Thanks in advance.
you need to pass the callback function to use the function wich you choose, the same with the modal
export const addProject = (flowerbed, flowerbedCallback, modalCallback) => {
flowerbed.key = Math.random().toString()
flowerbedCallback((currentFlowerbeds) => {
return [flowerbed, ...currentFlowerbeds]
})
modalCallback(false)
}
/** You need to invoce the method like this,
two parameters: setFlowerbed & setModalOpen, are functions but are not called
so you will can execute inside addProject function */
addProject(flowerbedExample, setFlowerbed, setModalOpen);
If you pass the function as parameter, when you call it, are you passing the method to his scope, vecause you are passaing the reference of the function, so when you executre the parameter callback you will execute the reference
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.