我想将 props(origin, destination) 传递到 Map.js 以用于 DirectionsRenderer

问题描述

我正在使用 DirectionsRenderer react-google-maps 库来渲染两点之间的目的地。我想在 Map.js 文件中传递原点和目的地的自定义道具, 这是我的代码

import React from 'react'
import { withScriptjs } from "react-google-maps";
import Map from './Map'

const Directions = ({ origin,destination }) => {

    const MapLoader = withScriptjs(props => <Map {...props} />);

  return (

<div className="App">
  <MapLoader
      googleMapURL="https://maps.googleapis.com/maps/api/js?key="
      loadingElement={<div style={{ height: `100%` }} />}
  />
</div>
  );
}

export default Directions


Map.js

    import React,{ useEffect,useState } from "react";
import {
    withGoogleMap,GoogleMap,DirectionsRenderer
} from "react-google-maps";

function Map({props})  {
    const [directions,setDirections] = useState(null)

   useEffect(() => {
    const google = window.google
    const directionsService = new google.maps.DirectionsService();

    const origin = { lat: 23.6238,lng: 90.5000};
    const destination = { lat: 23.8103,lng:  90.4125 }

    directionsService.route(
        {
            origin: origin,destination: destination,travelMode: google.maps.TravelMode.DRIVING,},(result,status) => {
            if (status === google.maps.Directionsstatus.OK) {
                console.log(result)
                setDirections(result)
            } else {
                console.error(`error fetching directions ${result}`);
            }
        }
    );
   },[])

    const GoogleMapExample = withGoogleMap(props => (
        <GoogleMap
            defaultCenter={{ lat: 23.8103,lng:  90.4125 }}
            defaultZoom={17}
        >
            <DirectionsRenderer
                directions={directions}
            />
        </GoogleMap>
    ));

    return (
        <div>
            <GoogleMapExample
                containerElement={<div style={{ height: `400px`,width: "500px" }} />}
                mapElement={<div style={{ height: `100%` }} />}
            />
        </div>
       );
    }

export default Map;

这里我想从根路由(Directions.js)获取目的地和起点。 有人告诉我如何将它作为道具传递给 Map.js。

解决方法

您不能在功能组件中完全使用 props,因为它们实际上仅用于基于类的组件中。但是有一种方法可以模仿它们的功能。由于您正在处理功能组件,因此您可能希望像已经在做的那样使用 React hooks (useState)。就像在基于类的组件中一样,在传递数据方面不会有太大区别。下面是一个代码片段,这里是一个示例:https://stackblitz.com/edit/directions-eo8c6v

index.js


    import React,{ Component } from "react";
    import { render } from "react-dom";
    import { withScriptjs } from "react-google-maps";
    import Map from "./Map";
    import "./style.css";
    
    const { useState } = React;
    const App = () => {
      const MapLoader = withScriptjs(Map);
      const [origin,setOrigin] = useState({ lat: 23.6238,lng: 90.5 });
      const [destination,setDestination] = useState({
        lat: 23.8103,lng: 90.4125
      });
    
      return (
        <MapLoader
          googleMapURL="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"
          loadingElement={<div style={{ height: `100%` }} />}
          origin={origin}
          destination={destination}
        />
      );
    };
    
    render(<App />,document.getElementById("root"));

Map.js


    import React,{ Component } from "react";
    import {
      withGoogleMap,withScriptjs,GoogleMap,DirectionsRenderer
    } from "react-google-maps";
    
    const { useEffect,useState } = React;
    
    function Map({ origin,destination }) {
      const [directions,setDirections] = useState(null);
    
      useEffect(() => {
        const google = window.google;
        const directionsService = new google.maps.DirectionsService();
    
        //const origin = { lat: 23.6238,lng: 90.5 };
        //const destination = { lat: 23.8103,lng: 90.4125 };
    
        directionsService.route(
          {
            origin: origin,destination: destination,travelMode: google.maps.TravelMode.DRIVING
          },(result,status) => {
            if (status === google.maps.DirectionsStatus.OK) {
              console.log(result);
              setDirections(result);
            } else {
              console.error(`error fetching directions ${result}`);
            }
          }
        );
      },[]);
    
      const GoogleMapExample = withGoogleMap(props => (
        <GoogleMap defaultCenter={{ lat: 23.8103,lng: 90.4125 }} defaultZoom={17}>
          <DirectionsRenderer directions={directions} />
        </GoogleMap>
      ));
    
      return (
        <div>
          <GoogleMapExample
            containerElement={<div style={{ height: `400px`,width: "500px" }} />}
            mapElement={<div style={{ height: `100%` }} />}
          />
        </div>
      );
    }
    
    export default Map;