我正在使用react-google-maps文档中发布的聚集地图的股票代码.我试图通过为标记添加一个click事件来扩展代码,该事件将从API中获取标记URL,然后调用window.location来更改页面. 以下是从我的
以下是从我的API返回的标记之一的示例:
{ id: 1, name: "Oxford", slug: "oxford", lat: 51.752021, lng: -1.257726, }
我已将一个事件onMarkerClick添加到标记中,并且正确调用该方法.我硬编码window.location并调用它,我只是不知道如何获取slug值.
我假设我必须存储slug值与我在下面的示例中的方式不同.我是React的新手,所以我可能错过了一些非常明显的东西
import React from 'react' const fetch = require("isomorphic-fetch"); const { compose, withProps, withHandlers } = require("recompose"); const { withScriptjs, withGoogleMap, GoogleMap, Marker } = require("react-google-maps"); const { MarkerClusterer } = require("react-google-maps/lib/components/addons/MarkerClusterer"); const MapWithAMarkerClusterer = compose( withProps({ googleMapURL: "https://maps.googleapis.com/maps/api/js?key=AIzaSyCvakAjEUpqfnucJu-CoClBD1CtTKZUGxQ&v=3.exp&libraries=geometry,drawing,places", loadingElement: <div style={{ height: 'calc(100vh - 56px)' }} />, containerElement: <div style={{ height: 'calc(100vh - 56px)' }} />, mapElement: <div style={{ height: 'calc(100vh - 56px)' }} />, }), withHandlers({ onMarkerClustererClick: () => (markerClusterer) => { console.log('Clicked a cluster') }, onMarkerClick: () => (marker) => { // link to post view page // // // // // console.log('Go to the marker post page') window.location = '/post/oxford'; } }), withScriptjs, withGoogleMap )(props => <GoogleMap defaultZoom={3} defaultCenter={{ lat: 12.2637937, lng: 75.947508 }} > <MarkerClusterer onClick={props.onMarkerClustererClick} averageCenter enableRetinaIcons gridSize={60} > {props.markers.map(marker => ( <Marker onClick={props.onMarkerClick} key={marker.id} position={{ lat: marker.lat, lng: marker.lng }} slug={marker.slug} /> ))} </MarkerClusterer> </GoogleMap> ); class TestMap extends React.PureComponent { componentWillMount() { this.setState({ markers: [] }) } componentDidMount() { const url = '/api/posts'; fetch(url) .then(res => res.json()) .then(data => { this.setState({ markers: data }); }); } render() { return ( <MapWithAMarkerClusterer markers={this.state.markers} /> ) } } export default TestMap您可以为标记创建自定义组件,并通过其他参数进行标识 – 例如,id:
import React from 'react'; import {Marker} from 'react-google-maps'; const CustomMarker = (props) => { const {id} = props; const onMarkerClick = (evt) => { console.log(id); }; return ( <Marker onClick={onMarkerClick} {...props} /> ); }; export default CustomMarker;