简体   繁体   English

如何在 React Native 的另一个函数中访问 c​​onst?

[英]How to access const inside another function in React Native?

I have a file called home.js that looks like this:我有一个名为home.js的文件,如下所示:

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 .在函数addProject我需要调用HomeScreen内的函数setFlowerbed ,但出现错误:找不到变量: setFlowerbed I cannot put function addProject inside HomeScreen because I need to access it in another file:我不能将函数addProject放在HomeScreen因为我需要在另一个文件中访问它:

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如果你将函数作为参数传递,当你调用它时,你是否将方法传递给了他的作用域,因为你传递的是函数的引用,所以当你执行参数回调时你会执行引用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM