You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MUI Dialog中@react-google-maps/api的Autocomplete组件两处问题咨询

问题1 解决方案

  • 出现遮挡是因为MUI v4的Dialog默认z-index为1300,而Google Maps自动生成的地址建议下拉容器(类名为.pac-container)默认z-index低于该值,导致被覆盖。
  • 修复方式:全局添加如下CSS样式即可:
/* 优先级高于MUI Dialog即可,1400足够覆盖默认Dialog层级 */
.pac-container {
  z-index: 1400 !important;
}

问题2 解决方案

这个报错常见有两个原因,对应修复方式如下:

  1. 组件方法调用混淆
    @react-google-maps/api 下的 Autocomplete 组件仅提供 getPlace() 方法(返回单个选中的地址对象),getPlaces() 是同库 SearchBox 组件的方法,如果你的场景用的是Autocomplete而非SearchBox,把调用方法改成autocomplete.getPlace()即可解决。
  2. 调用时机错误
    只有当用户主动选中下拉列表中的地址选项后,对应方法才会生效。如果用户未选中选项直接回车提交,实例不会挂载对应方法,需要加判断做兼容,示例代码如下:
import { useRef } from 'react';
import { Autocomplete } from '@react-google-maps/api';

const YourComponent = () => {
  // 存储Autocomplete实例
  const autocompleteRef = useRef(null);
  // 输入框ref用来拿未选中时的输入内容
  const inputRef = useRef(null);

  // 组件加载完成后存储实例
  const handleAutoCompleteLoad = (autocompleteInstance) => {
    autocompleteRef.current = autocompleteInstance;
  };

  const handleSubmit = () => {
    let placeData = null;
    // 先判断方法是否存在
    if (autocompleteRef.current && typeof autocompleteRef.current.getPlace === 'function') {
      placeData = autocompleteRef.current.getPlace();
    }
    if (placeData) {
      // 正常处理选中的地址逻辑
      console.log('选中的地址:', placeData);
    } else {
      // 兼容逻辑:拿输入框内容做后续处理,或给用户提示
      const inputValue = inputRef.current.value;
      console.log('用户输入的内容:', inputValue);
    }
  };

  return (
    <Autocomplete onLoad={handleAutoCompleteLoad}>
      <input ref={inputRef} type="text" onKeyPress={(e) => e.key === 'Enter' && handleSubmit()} />
    </Autocomplete>
  )
}

内容的提问来源于stack exchange,提问作者Jabal Logian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 22:45:03