首页 > 解决方案 > TypeError:在 React 组件中使用 Google Location API 时无法读取未定义的属性“位置”

问题描述

我正在尝试将 Google 位置 API 配置为在表单输入中使用。我收到以下错误:

类型错误

我在 index.html 文件中使用以下脚本标记:

脚本标签

这是我尝试在其中使用 Google API 的组件的代码:

import React from 'react'
/* global google */
const google = window.google = window.google ? window.google : {}

import { FormContainer, ModalTextInput } from './styles'
import '../styles.css'
import { Modal, Button, Form } from 'react-bootstrap'

import TelInput from './IntlTelInput'

class EditDetailsModal extends React.Component {

    constructor(props) {
    super(props);
    this.autocompleteInput = React.createRef();
    this.autocomplete = null;
    this.handlePlaceChanged = this.handlePlaceChanged.bind(this);
  }

  componentDidMount() {
    this.autocomplete = new google.maps.places.Autocomplete(this.autocompleteInput.current,
        {"types": ["geocode"]});

    this.autocomplete.addListener('place_changed', this.handlePlaceChanged);
  }

  handlePlaceChanged(){
    const place = this.autocomplete.getPlace();
    this.props.onPlaceLoaded(place);
  }

  render() {
    return (
          <Modal show={this.props.show} onHide={this.props.handleClose} className="editModal">
                <FormContainer>
                    <Modal.Header className="editModalHeader">
                      <Modal.Title>Edit Personal Details</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        <Form>
                          <Form.Group controlId="formBasicName">
                            <ModalTextInput customPlaceholder="Name"/>
                          </Form.Group>

                          <Form.Group controlId="formBasicEmail">
                            <ModalTextInput customPlaceholder="Email ID"/>
                          </Form.Group>

                          <Form.Group controlId="formBasicPhoneNumber">
                          <TelInput className="formInput"/>
                          </Form.Group>
                          <Form.Group controlId="formBasicName">
                            <ModalTextInput ref={this.autocompleteInput} customPlaceholder="Country you will work in"/>
                          </Form.Group>
                          <Button variant="primary" type="submit" className="submitBtn">
                            Save details
                          </Button>
                        </Form>
                </Modal.Body>
                </FormContainer>
        </Modal>
      )
  }

}

export default EditDetailsModal

我尝试了许多修复程序,但它们似乎不起作用。

标签: javascriptreactjsgoogle-maps-api-3

解决方案


推荐阅读