如何在React Native中从孙子传达到祖父母然后再回传给祖父母的孩子

时间:2019-10-07 15:59:59

标签: reactjs react-native react-hooks react-props

我是React的新手,所以我希望我能正确解决这个问题。首先,我有一个名为 SearchLocationsScreen 的屏幕。在该屏幕中,我有一个名为 Map 的组件,在 Map 中有一个名为 LocationMarker 的自定义标记组件。在与 Map 组件相同的层次结构级别上,我有一个名为 CheckinModal 的自定义ModalBox。这是一个粗略的图表可以帮助您:

enter image description here

SearchLocationsScreen 中,我从API调用中获取位置信息。然后,将这些位置传递到我的地图组件中。在我的地图组件中,将标记的信息向下传递到自定义的 LocationMarker 类,然后填充地图。

目标是按下一个标记,并从底部弹出 CheckinModal ,并使用所按下的特定标记的信息填充它。为此,我使用 useRef 钩子和 forwardRef 钩子将对模式的引用向下传递给 LocationMarker 类。在这里,我称为ref.current.open(),并且模式将按预期方式打开。

问题是我无法找到一种方法来从标记传递位置信息,将层次结构备份到屏幕上,再向下到模态以用相关信息填充模态。有谁知道如何实现这一目标?我将下面的代码发布到屏幕,地图组件和标记组件(不包括样式)。预先感谢您的帮助。

SearchLocationsScreen.js

const SearchLocationsScreen = ({isFocused, navigation}) => {

    const {updateLocation} = useContext(CurrentLocationContext);

    // hooks
    const callback = useCallback((location) => {
        updateLocation(location)
    }, []);
    const [err] = useCurrentLocation(isFocused, callback);
    const [businessLocations] = useGetLocations();

    const modalRef = useRef(null);

    let locations = [];

    if (businessLocations) {
        for (let x = 0; x < businessLocations.length; x++) {
            locations.push({
                ...businessLocations[x],
                latitude: businessLocations[x].lat,
                longitude: businessLocations[x].lng,
                key: x,
            })
        }
    }

    return (
        <View style={{flex: 1}}>

            <Map markers={locations} ref={modalRef}/>

            <SearchBar style={styles.searchBarStyle}/>

            {err ? <View style={styles.errorContainer}><Text
                style={styles.errorMessage}>{err.message}</Text></View> : null}

            <CheckinModal
                ref={modalRef}
            />

        </View>
    );
};

Map.js

    const Map = ({markers}, ref) => {

        const {state: {currentLocation}} = useContext(Context);

        // todo figure out these error situations
        if (!currentLocation) {
            return (
                <View style={{flex: 1}}>
                    <MapView
                        style={styles.map}
                        provider={PROVIDER_GOOGLE}
                        initialRegion={{
                            latitude: 27.848680,
                            longitude: -82.646560,
                            latitudeDelta: regions.latDelta,
                            longitudeDelta: regions.longDelta
                        }}
                    />

                    <ActivityIndicator size='large' style={styles.indicator} />
                </View>
            )
        }

        return (

            <MapView
                style={styles.map}
                provider={PROVIDER_GOOGLE}
                initialRegion={{
                    ...currentLocation.coords,
                    latitudeDelta: regions.latDelta,
                    longitudeDelta: regions.longDelta
                }}
                showsUserLocation
                >

                { markers ? markers.map((marker, index) => {
                    return <LocationMarker
                        ref={ref}  // passing the ref down to the markers
                        key={index}
                        coordinate={marker}
                        title={marker.company}
                        waitTime={ marker.wait ? `${marker.wait} minutes` : 'Open'}
                    />;
                }) : null}

            </MapView>
        )
    };

    const forwardMap = React.forwardRef(Map);

    export default forwardMap;

LocationMarker.js

const LocationMarker = ({company, coordinate, title, waitTime, onShowModal}, ref) => {
    return (
        <View>
            <Marker
                coordinate={coordinate}
                title={title}
                onPress={() => {
                    console.log(ref);
                    ref.current.open();
                }}
            >
                <Image
                    source={require('../../assets/marker2.png')}
                    style={styles.locationMarker}/>
                <View style={styles.waitContainer}><Text style={styles.waitText}>{waitTime}</Text></View>
            </Marker>

        </View>
    )
};

const forwardMarker = React.forwardRef(LocationMarker);

export default forwardMarker;

3 个答案:

答案 0 :(得分:1)

如果我理解正确,建议不要使用apt-get update道具通过forwardRef传递来自父母的裁判,而是建议将其作为简单的道具传递。当它到达嵌套组件(在您的情况下为 LocationMarker )时,您可以对其进行分配。这是一个简化的版本:

ref

当ref到达最后一个元素时,我们使用const SearchLocationsScreen = props => { const marker_ref = useRef(null); const modal_ref = useRef(null); return ( <View> <Map marker_ref={marker_ref} modal_ref={modal_ref} /> <CheckinModal marker_ref={marker_ref} modal_ref={modal_ref} /> </View> ); }; const Map = props => { const { marker_ref, modal_ref } = props; return <LocationMarker marker_ref={marker_ref} modal_ref={modal_ref} />; }; const LocationMarker = props => { const { marker_ref, modal_ref } = props; return <div ref={marker_ref} />; }; const CheckinModal = props => { const { marker_ref, modal_ref } = props; return <div ref={modal_ref} />; }; 对其进行分配。请记住,最后一个元素必须是JSX元素(例如ref=),而不是组件。

为避免将这些道具从祖父母那里传递到孩子之间的每个组件中,可以在div中使用Context

答案 1 :(得分:0)

您是否考虑过使用挂钩?挂钩使您可以在功能上组成组件,而不必通过props传递所有内容。如果您需要在多个地方使用此值,可能会使您的生活更轻松?在您遇到的情况下,您可以将钩子放置在一个位置,然后在其更改时更新另一个组件,而不必担心传递任何东西

https://reactjs.org/docs/hooks-intro.html

答案 2 :(得分:0)

我在Alvaro对我的主要帖子的评论的帮助下找到了答案。

这就是我所做的。首先,我将生成 LocationMarker 的代码移至 SearchLocationsScreen 。无论如何,我已经在该屏幕上访问了这些标记所需的位置(最初我将这些位置向下传递到 Map 组件并在那里创建它们)。在 SearchLocationsScreen 中,我遍历所有位置以生成 LocationMarker ,并添加一个回调,该回调使用 useReducer 钩子存储模式的状态。由于它们都处于同一级别,因此我可以使用来自化简器状态的正确数据填充模态的字段。该回调将传递给 LocationMarker 。然后在 LocationMarker onPress中,我调用此方法。一切正常。这是更新的代码:

SearchLocationsScreen

const SearchLocationsScreen = ({isFocused, navigation}) => {

    const {updateLocation} = useContext(CurrentLocationContext);

    // hooks
    const callback = useCallback((location) => {
        updateLocation(location)
    }, []);
    const [err] = useCurrentLocation(isFocused, callback);
    const [businessLocations] = useGetLocations();
    const modalRef = useRef(null);

    let locations = [];

    if (businessLocations) {
        for (let x = 0; x < businessLocations.length; x++) {
            locations.push({
                ...businessLocations[x],
                latitude: businessLocations[x].lat,
                longitude: businessLocations[x].lng,
                key: x,
            })
        }
    }

    const modalReducer = (state, action) => {
        console.log("payload: ", action.payload);
        switch (action.type) {
            case 'show_modal':
                return {...state,
                    companyName: action.payload.companyName,
                    companyAddress: action.payload.companyAddress,
                    waitTime: action.payload.waitTime
                };
            default:
                return state;
        }
    };

    const [modalState, dispatch] = useReducer(modalReducer, {
        companyName: "Company Name",
        companyAddress: "123 Elm St",
        waitTime: 0
    });

    const createMarkers = () => {
        let result = [];
        if (locations) {
            for (let i = 0; i < locations.length; i++) {
                result.push(
                    <LocationMarker
                        key={i}
                        id={i}
                        coordinate={locations[i]}
                        title={locations[i].company}
                        waitTime={locations[i].wait ? `${locations[i].wait} minutes` : 'Closed'}
                        onShowModal={() => {
                            dispatch({
                                type: 'show_modal', payload: {
                                    companyName: locations[i].company,
                                    companyAddress: locations[i].address,
                                    waitTime: locations[i].wait,
                                }
                            });
                            modalRef.current.open();
                        }}
                    />
                )
            }
        }
        return result;
    };

    return (
        <View style={{flex: 1}}>

            <Map markers={createMarkers()}/>
            {/*<Map ref={modalRef} markers={...createMarkers()} />*/}

            <SearchBar style={styles.searchBarStyle}/>

            {err ? <View style={styles.errorContainer}><Text
                style={styles.errorMessage}>{err.message}</Text></View> : null}

            <CheckinModal
                ref={modalRef}
                businessName={modalState.companyName}
                address={modalState.companyAddress}
                waitTime={modalState.waitTime}
            />

        </View>
    );
};

地图

const Map = ({markers}, ref) => {

    const {state: {currentLocation}} = useContext(Context);

    return (

        <MapView
            style={styles.map}
            provider={PROVIDER_GOOGLE}
            initialRegion={{
                ...currentLocation.coords,
                latitudeDelta: regions.latDelta,
                longitudeDelta: regions.longDelta
            }}
            showsUserLocation
            >

            {markers ? markers.map((marker, index) => {
                return marker;
            }): null}

        </MapView>
    )
};

export default Map;

CheckinModal

const CheckinModal = ({businessName, address, waitTime}, ref) => {

    return (
            <ModalBox
                style={styles.modal}
                position={'bottom'}
                backdrop={true}
                ref={ref}
            >
                <Text>Store Name: {businessName}</Text>
                <Text>Store Address: {address}</Text>
                <Text>Wait time: {waitTime} minutes</Text>
            </ModalBox>
    )
};

const forwardModal = React.forwardRef(CheckinModal);
export default forwardModal;

LocationMarker

const LocationMarker = (props) => {

    return (
        <View>
            <Marker
                coordinate={props.coordinate}
                title={props.title}
                id={props.id}
                onPress={() => {
                    props.onShowModal();
                }}
            >
                <Image
                    source={require('../../assets/marker2.png')}
                    style={styles.locationMarker}/>
                <View style={styles.waitContainer}>
                    <Text style={styles.waitText}>{props.waitTime}</Text>
                </View>
            </Marker>

        </View>
    )
};

export default LocationMarker;

有了这个新代码,我不必转发太多引用,而只需转发到 CheckinModal

如果有人有任何问题,请将其发布在此答案下方,我将尝试尽快回答。谢谢大家的帮助。