反应本机模态回调-将道具传递给父级

时间:2019-10-28 20:38:27

标签: react-native callback parent-child react-hooks react-native-navigation

我正在使用React Native Modal,并且很难将道具从Modal传递回称为Modal的类。

我尝试使用onRequestClose()onPress()并为回调数据googlePlacesPassedBackLocation设置道具,但没有成功。我正在尝试从GooglePlaces检索pastLocations。我可以在GooglePlaces中看到位置生成正确。我在Modal类和GooglePlaces类中都使用useState挂钩。

我读到,这很难做,因为react并不能真正支持它。有可能吗?

import {StyleSheet, View, Modal, TouchableOpacity, Text, TouchableHighlight, Button } from 'react-native';

父项:

const RegisterLocationScreen = ({navigation}) => {  
    var [pastLocations, setPastLocations] = useState([]);
    var [pastModalVisible, setModalPastVisible] = useState(false);

    const closeModal = (timeFrame) => {
        setModalPastVisible(false);
    };
    const openGooglePastModal = () => {
        setModalPastVisible(true)
    };

    return (
    <Modal visible={pastModalVisible} animationType={'slide'} onRequestClose={() => closeModal(pastLocations)}>
        <View style={styles.modalContainer}>
            <SafeAreaView style = {styles.safeAreaViewStyle} forceInset={{top: 'always'}}>
                 <GooglePlaces timePeriod="Past" googlePlacesPassedBackLocation={googlePlacesPassedBackLocation} />
                 <TouchableOpacity style = {styles.buttonContainer} onPress={()=> closeModal('Past')}> 
                        <Text style={styles.buttonText} >
                            Close Modal
                        </Text>
                 </TouchableOpacity>                        
            </SafeAreaView>
        </View>
    </Modal>
    <TouchableOpacity style = {styles.buttonModal} onPress={() => openGooglePastModal()} >
            <Text style={styles.buttonModalText} >
                Past Locations 
            </Text>
    </TouchableOpacity>

子组件:

import React, {useState} from 'react';
import {StyleSheet } from 'react-native'
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';

const API_KEY = '123omittedforsecurity';

const GooglePlaces = ({timePeriod}) => { 
    var [pastLocations, setPastLocations] = useState([]);

    const updateLocationArray = (data, details) =>{
        setPastLocations([
            ...pastLocations,
            details.geometry.location
          ]);        
    };

    return (
    <GooglePlacesAutocomplete
        placeholder={timePeriod}
        onPress={(data, details) => { 
            updateLocationArray(data, details);
        }}
        ..../>

0 个答案:

没有答案