簡體   English   中英

谷歌地圖反應標記 onclick 不工作

[英]google-map-react marker onclick not working

為了清楚起見,我正在使用 react-google-map https://www.npmjs.com/package/google-map-react

我清楚地遵循了文檔,並且能夠使其正常工作。 這是我的代碼。

import React from 'react';
import GoogleMapReact from 'google-map-react';
import {Avatar, Box, Text, useColorModeValue, VStack} from "@chakra-ui/react";

const Marker = ({text}) => (
    <VStack alignItems={'center'}>
        <Avatar backgroundColor={useColorModeValue('#5125b6', '#99c3ff')} w={5} h={5} name={' '}/>
        <Text>{text}</Text>
    </VStack>
);
function Map() {
    return (
        <Box mt={5} style={{height: '60vh', width: '100%'}}>
            <GoogleMapReact
                bootstrapURLKeys={{key: 'mymapskey'}}
                defaultCenter={[0, 0]}
                defaultZoom={2}
            >
                <Marker
                    lat={59.955413}
                    lng={30.337844}
                    text="hehe"
                    onClick={console.log('haha')}
                />
            </GoogleMapReact>
        </Box>
    );
}

export default Map;

由於某些原因。 標記 onClick 不會觸發。 所以當我點擊標記時。 什么都沒發生。 我的控制台上什么也沒有發生。 我不確定我做錯了什么。 任何幫助將不勝感激。

這僅僅是因為<Marker />組件不能將onClick作為道具。 相反,您應該將onChildClick添加到<GoogleMapReact />並使用他們的key屬性確定哪個孩子。

<GoogleMapReact
  bootstrapURLKeys={{ key: 'mymapskey' }}
  defaultCenter={[0, 0]}
  defaultZoom={2}
  onChildClick={(key) => console.log(key, 'haha')}
>
  <Marker lat={59.955413} lng={30.337844} key="your-key-for-this-marker" />
</GoogleMapReact>

我對代碼進行了這些更改,它可以工作!


import React from 'react';
import GoogleMapReact from 'google-map-react';
import {Avatar, Box, Text, useColorModeValue, VStack} from "@chakra-ui/react";

const Marker = ({text}) => (
    <VStack onClick={console.log(text)} alignItems={'center'}>
        <Avatar backgroundColor={useColorModeValue('#5125b6', '#99c3ff')} w={5} h={5} name={' '}/>
        <Text>{text}</Text>
    </VStack>
);
function Map() {
    return (
        <Box mt={5} style={{height: '60vh', width: '100%'}}>
            <GoogleMapReact
                bootstrapURLKeys={{key: 'mymapskey'}}
                defaultCenter={[0, 0]}
                defaultZoom={2}
            >
                <Marker
                    lat={59.955413}
                    lng={30.337844}
                    text="hehe"
                />
            </GoogleMapReact>
        </Box>
    );
}

export default Map;

暫無
暫無

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

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