无法从 react-google-maps/api 中的 StandaloneSearchBox 访问 this.searchBox

Cannot access this.searchBox from StandaloneSearchBox in react-google-maps/api

我正在尝试访问 getPlaces() 函数,该函数应该位于 react-google-maps/apiStandaloneSearchBox 组件中。在 documentation 和其他示例中,它们是这样使用的:

function Map() {

 // does not work.
 // Error -> 'this' implicitly has type 'any' because it does not have a type 
 // annotation.ts(2683)
 // index.tsx(22, 10): An outer value of 'this' is shadowed by this container.
 const onPlacesChanged = () => console.log(this.searchBox.getPlaces());

  return (
    <LoadScript
      googleMapsApiKey="YOUR-API-KEY"
      libraries={places}
    >
      <GoogleMap
        mapContainerStyle={containerStyle}
        center={center}
        zoom={zoom}
      >
        { /* Child components, such as markers, info windows, etc. */}
        <>
          <StandaloneSearchBox onPlacesChanged={onPlacesChanged} >
            <input
              type='text'
              placeholder='Customized your placeholder'
              style={{
                boxSizing: 'border-box',
                border: `1px solid transparent`,
                width: `270px`,
                height: `40px`,
                padding: `0 12px`,
                borderRadius: `3px`,
                boxShadow: `0 2px 6px rgba(0, 0, 0, 0.3)`,
                fontSize: `14px`,
                outline: `none`,
                margin: 'center',
                textOverflow: `ellipses`,
                position: 'absolute',
                top: '40px',
                marginLeft: '50%'
              }}
            />
          </StandaloneSearchBox>
        </>
      </GoogleMap>
    </LoadScript>
  )
}

我正在尝试这种方式,因为这是我设法在该函数中获得 this 的唯一方法:

// ... all the same 

// does not work either, this is a strange object and "searchBox" does not exists in it
function onPlacesChanged(this: any) {
     console.log(this.searchBox.getPlaces())
  }

// ... all the same

但是我无法从 this 访问 searchBox 属性。当我打印 this 时,它显示了一个很大的奇怪对象,其属性类似于`{e3: {…}, gm_bindings :{…},gm_accessors_:{…}}

有人遇到过这个问题吗?

documentation中,函数onPlacesChanged是这样描述的:

onPlacesChanged (() => void) | undefined 

Description:    This event is fired when the user selects a query, getPlaces should be used to get new places.

以下是有关如何使您的代码正常工作的建议:

  1. 我看到您在代码中使用了功能组件。您不能在功能组件中使用 this。您可以改用 useState。 您可以使用 const [searchBox, setSearchBox] = useState(null);

    而不是 this.searchBox
  2. 获得 useState 后,使用 SearchBox 的 onLoad 属性调用一个函数,将 Searchbox 对象的 ref 设置为搜索框状态。

  3. 在您的 onPlacesChanged 中,您只需记录 searchBox.getPlaces() 即可获得 getPlaces 的结果。

这是 working code 和代码片段:

/*global google*/
import ReactDOM from 'react-dom';
import React, { useState } from 'react';

import {
  GoogleMap,
  StandaloneSearchBox,
  LoadScript
} from '@react-google-maps/api';
const lib = ['places'];
const center = { lat: 40.756795, lng: -73.954298 };
function Map() {
  const [searchBox, setSearchBox] = useState(null);

  const onPlacesChanged = () => console.log(searchBox.getPlaces());
  const onSBLoad = ref => {
    setSearchBox(ref);
  };

  return (
    <LoadScript
      googleMapsApiKey="YOUR_KEY"
      libraries={lib}
    >
      <GoogleMap
        mapContainerStyle={{ height: '400px', width: '800px' }}
        center={center}
        zoom={12}
      >
        {/* Child components, such as markers, info windows, etc. */}
        <>
          <StandaloneSearchBox
            onPlacesChanged={onPlacesChanged}
            onLoad={onSBLoad}
          >
            <input
              type="text"
              placeholder="Customized your placeholder"
              style={{
                boxSizing: 'border-box',
                border: `1px solid transparent`,
                width: `270px`,
                height: `40px`,
                padding: `0 12px`,
                borderRadius: `3px`,
                boxShadow: `0 2px 6px rgba(0, 0, 0, 0.3)`,
                fontSize: `14px`,
                outline: `none`,
                margin: 'center',
                textOverflow: `ellipses`,
                position: 'absolute',
                top: '40px',
                marginLeft: '50%'
              }}
            />
          </StandaloneSearchBox>
        </>
      </GoogleMap>
    </LoadScript>
  );
}
export default Map;