簡體   English   中英

如何在 React Native 的另一個函數中訪問 c​​onst?

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

我有一個名為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>
)
}

在函數addProject我需要調用HomeScreen內的函數setFlowerbed ,但出現錯誤:找不到變量: setFlowerbed 我不能將函數addProject放在HomeScreen因為我需要在另一個文件中訪問它:

import { addProject } from './screens/home';

有沒有辦法解決這個錯誤? 提前致謝。

您需要傳遞回調函數以使用您選擇的函數,與模態相同

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);

如果你將函數作為參數傳遞,當你調用它時,你是否將方法傳遞給了他的作用域,因為你傳遞的是函數的引用,所以當你執行參數回調時你會執行引用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM