首页 > 解决方案 > Google Places Autocomplete 容器未固定到其关联的输入元素

问题描述

我在我的 NextJS 应用程序中创建了一个可重用的组件“SearchBar”,它通过脚本加载 Google 自动完成功能并且没有第三方库。

我在我的主页上使用了这个组件来搜索用户想要的位置。现在我也尝试在标题中使用这个组件,它也可以工作,但是我无法让带有搜索结果的容器(CSS 中的 pac-container)与输入保持一致。

在主页上这很好用,但是如果我在标题的输入中搜索一个位置并且 pac-container 出现,它会留在屏幕上,并且相对于其输入元素不会保持固定位置。

我已经尝试过所有已知的 Z 索引和位置组合,如“固定”等,但不幸的是我找不到解决方案。

我的 CSS 的很大一部分是用 Tailwind ( https://tailwindcss.com )完成的

有没有人有任何想法?

let autoComplete;

export const loadScript = (url, callback) => {
  let script = document.createElement("script");
  script.type = "text/javascript";

  if (script.readyState) {
    script.onreadystatechange = function () {
      if (script.readyState === "loaded" || script.readyState === "complete") {
        script.onreadystatechange = null;
        callback();
      }
    };
  } else {
    script.onload = () => callback();
  }

  script.src = url;
  document.getElementsByTagName("head")[0].appendChild(script);
};

export function handleScriptLoad(updateQuery, autoCompleteRef) {
  autoComplete = new window.google.maps.places.Autocomplete(
    autoCompleteRef.current,
    { types: ["(cities)"] }
  );
  autoComplete.setFields(["address_components", "formatted_address"]);
  autoComplete.addListener("place_changed", () =>
    handlePlaceSelect(updateQuery)
  );
}

export async function handlePlaceSelect(updateQuery) {
  const addressObject = autoComplete.getPlace();
  const query = addressObject.formatted_address;
  updateQuery(query);
  console.log(addressObject);
}
html,
body {
  padding: 0;
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
    Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
}

a {
  color: inherit;
  text-decoration: none;
}

* {
  box-sizing: border-box;
}

.pac-container {
  position: relative;
  z-index: 0;
  background-color: #fff;
  border-radius: 0px;
  border: 2px solid #060606;
  margin-top: 10px;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  box-shadow: none;
}

.pac-item:hover {
  background-color: #eeeeee;
  cursor: pointer;
}
.pac-item-selected,
.pac-item-selected:hover {
  background-color: #ebf2fe;
}

.pac-item {
  height: 50px;
  font-family: Poppins;
  font-size: 13px;
  padding: 5px;
  padding-left: 10px;
  padding-top: 10px;
}

.pac-placeholder {
  color: gray;
}

.pac-container:after {
  background-image: none !important;
  height: 0px;
}

.pac-icon {
  background: url("/icons/locationIcon.svg") no-repeat center;
  background-size: 16px;
  margin: 5px 10px 6px 0;
  vertical-align: middle;
}
import { useState, useEffect, useRef } from "react";
import LocationIcon from "../public/icons/locationIcon.svg";
import { loadScript, handleScriptLoad } from "../services/google";

interface Props {
  query: string;
  setQuery: (event) => void;
}

export const SearchBar = ({ query, setQuery }: Props) => {
  const autoCompleteRef = useRef(null);
  const [isSearchFocused, setIsSearchFocused] = useState(false);

  useEffect(() => {
    loadScript(
      `https://maps.googleapis.com/maps/api/js?key=${process.env.NEXT_PUBLIC_GOOGLE_PLACES_API}&libraries=places`,
      () => handleScriptLoad(setQuery, autoCompleteRef)
    );
  }, []);

  return (
    <div
      className="flex items-center w-full xl:w-1/3 h-12 mr-2 bg-gray-100 pl-3 rounded-none mb-2 lg:w-1/3 lg:mb-0"
      style={isSearchFocused ? { borderColor: "black", borderWidth: 2 } : {}}
    >
      <LocationIcon className="w-5 h-5 text-left" />
      <input
        placeholder="placeholder"
        ref={autoCompleteRef}
        onChange={(event) => setQuery(event.target.value)}
        value={query}
        className="w-full ml-3 bg-gray-100 h-11 font-poppins placeholder-black outline-none"
        onFocus={() => setIsSearchFocused(true)}
        onBlur={() => setIsSearchFocused(false)}
      />
    </div>
  );
};

标签: javascripthtmlcssreactjs

解决方案


推荐阅读