首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >'MyMaps‘不能用作JSX组件

'MyMaps‘不能用作JSX组件
EN

Stack Overflow用户
提问于 2022-07-06 00:46:47
回答 1查看 165关注 0票数 0

如标题所示,我不能使用MyMaps作为JSX组件..。这是整个错误消息。

'MyMaps‘不能用作JSX组件。它的返回类型'void‘不是一个有效的JSX元素。

下面是发生错误的index.tsx文件的代码

代码语言:javascript
复制
import MyMaps from '../components/maps/maps';

// ...

export default function Index() {
  return (
    {/* ... */}

    <MyMaps />

    {/* ... */}
  )
}

编辑以添加Mymaps文件maps.jsx

代码语言:javascript
复制
import React from 'react';
import {
  GoogleMap,
  useLoadScript,
  Marker,
  InfoWindow,
} from '@react-google-maps/api';
import usePlacesAutocomplete, {
  getGeocode,
  getLatLng,
} from 'use-places-autocomplete';
import {
  Combobox,
  ComboboxInput,
  ComboboxPopover,
  ComboboxList,
  ComboboxOption,
} from '@reach/combobox';

import '@reach/combobox/styles.css';
import MapStyle from './mapStyles';
import Electronics from './Electronics_Drop_Off_NYC';

/// /////////////////////////////////////////////////////////////
const libraries = ['places'];
const mapContainerStyle = {
  position: 'relative',
  top: '120px',
  left: '40px',
  right: '40px',
  bottom: '200px',
};
const options = {
  styles: MapStyle,
  disableDefaultUI: true,
  zoomControl: true,
};
const center = {
  lat: 40.7703,
  lng: -73.9883,
};

// Get location from the browser function
function Locate({ panTo }) {
  return (
    <button
      className=" absolute right-4 top-4 z-10 flex w-8 mt-28 self"
      onClick={() => {
        navigator.geolocation.getCurrentPosition(
          (position) => {
            panTo({
              lat: position.coords.latitude,
              lng: position.coords.longitude,
            });
          },
          () => null
        );
      }}
    >
      <img src="/compass.svg" alt="Locate yourself" />
    </button>
  );
}

// Search function with input and list result
function Search({ panTo }) {
  const {
    ready,
    value,
    suggestions: { status, data },
    setValue,
    clearSuggestions,
  } = usePlacesAutocomplete({
    requestOptions: {
      location: { lat: () => 40.7703, lng: () => -73.9883 },
      radius: 50 * 1000,
    },
  });

  // https://developers.google.com/maps/documentation/javascript/reference/places-autocomplete-service#AutocompletionRequest

  const handleInput = (e) => {
    setValue(e.target.value);
  };

  const handleSelect = async (address) => {
    setValue(address, false);
    clearSuggestions();

    try {
      const results = await getGeocode({ address });
      const { lat, lng } = await getLatLng(results[0]);
      panTo({ lat, lng });
    } catch (error) {
      // eslint-disable-next-line no-console
      console.log(' Error: ', error);
    }
  };

  return (
    <div className="search">
      <Combobox onSelect={handleSelect}>
        <ComboboxInput
          value={value}
          onChange={handleInput}
          disabled={!ready}
          placeholder="Search your location here!"
        />
        <ComboboxPopover>
          <ComboboxList>
            {status === 'OK' &&
              data.map(({ id, description }) => (
                <ComboboxOption key={id} value={description} />
              ))}
          </ComboboxList>
        </ComboboxPopover>
      </Combobox>
    </div>
  );
}

export default function MyMaps() {
  const { isLoaded, loadError } = useLoadScript({
    googleMapsApiKey: process.env.NEXT_PUBLIC_MAPS_API,
    libraries,
  });
  const [, setMarkers] = React.useState([]);
  const [selected, setSelected] = React.useState(null);

  // This hook is not going to be used
  // This hook creates a marker whenever the user clicks and add info to the infobox.
  const onMapClick = React.useCallback(() => {
    setMarkers((current) => [...current]);
  }, []);

  const mapRef = React.useRef();
  const onMapLoad = React.useCallback((map) => {
    mapRef.current = map;
  }, []);
  // Hook to move the maps depending on user input location and zoom to that location
  const panTo = React.useCallback(({ lat, lng }) => {
    mapRef.current.panTo({ lat, lng });
    mapRef.current.setZoom(14);
  }, []);

  if (loadError) return 'Error';
  if (!isLoaded) return 'Loading...';

  return (
    <div className=" justify-center object-center">
      <Locate panTo={panTo} />
      <Search panTo={panTo} />

      <GoogleMap
        id="map"
        className="mapContainerStyle ml-10 justify-center content-center"
        mapContainerStyle={mapContainerStyle}
        zoom={10}
        center={center}
        options={options}
        onClick={onMapClick}
        onLoad={onMapLoad}
      >
        {Electronics.features.map((dropOff) => (
          <Marker
            key={dropOff.properties.zipcode}
            position={{
              lat: dropOff.geometry.coordinates[1],
              lng: dropOff.geometry.coordinates[0],
            }}
            onClick={() => {
              setSelected(dropOff);
            }}
            icon={{
              url: `/recycling.png`,
              origin: new window.google.maps.Point(0, 0),
              anchor: new window.google.maps.Point(15, 15),
              scaledSize: new window.google.maps.Size(30, 30),
            }}
          />
        ))}

        {selected ? (
          <InfoWindow
            position={{
              lat: selected.geometry.coordinates[1],
              lng: selected.geometry.coordinates[0],
            }}
            onCloseClick={() => {
              setSelected(null);
            }}
          >
            <div>
              <h2>
                <span role="img" aria-label="Recycling">
                  ♻️
                </span>{' '}
                {selected.properties.dropoff_sitename}{' '}
                <span role="img" aria-label="Recycling">
                  ♻️
                </span>
              </h2>
              <p> Address: {selected.properties.address} </p>
              <p> </p>
            </div>
          </InfoWindow>
        ) : null}
      </GoogleMap>
    </div>
  );
}

这是我的package.json,我使用的是Reactive17.0.2,因为我在另一个与此相关的问题上看到,它可能解决问题,但对我来说并非如此。

代码语言:javascript
复制
 "dependencies": {
    "@reach/combobox": "^0.17.0",
    "@react-google-maps/api": "^2.12.0",
    "@types/google-map-react": "^2.1.7",
    "next": "^12.1.0",
    "next-seo": "^5.2.0",
    "react": "^17.0.2",
    "react-bootstrap": "^2.4.0",
    "react-dom": "^17.0.2",
    "react-faq-component": "^1.3.4",
    "styled-components": "^5.3.5",
    "use-places-autocomplete": "^4.0.0"
  },
  "devDependencies": {
    "@fullhuman/postcss-purgecss": "^4.1.3",
    "@next/bundle-analyzer": "^12.1.0",
    "@types/google.maps": "^3.49.2",
    "@types/jest": "^28.1.3",
    "@types/node": "^17.0.23",
    "@types/react": "^17.0.2",
    "@types/react-dom": "^17.0.2",
},
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-06 13:51:15

只是解决了问题..。

MyMaps组件maps.jsx文件的错误输出如下

代码语言:javascript
复制
  if (loadError) return 'Error';
  if (!isLoaded) return 'Loading...';

而不是这种方式,这是JSX的方式。

代码语言:javascript
复制
  if (loadError) {
    return <div>Map cannot be loaded right now, sorry.</div>;
  }
  if (!isLoaded) {
    return <div>Loading...</div>;
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72876882

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档