如何为react-google-places-autocomplete添加自定义选项?
如何给GooglePlacesAutocomplete添加自定义选项?
我想给GooglePlacesAutocomplete添加自定义选项“Remote”,让它成为第一个选项,但尝试了多种方法都没成功,地址选项能正常显示,但自定义选项加不上。
我试过的方法:
autocompletionRequest={{ componentRestrictions: { country: 'AU' }, types: ['(regions)', 'Remote'], }}
还尝试直接添加option,也没用。有没有人实现过这个需求?我需要默认添加“Remote”作为位置选项,因为网站需要提供远程位置的选择。
我的组件代码:
<GooglePlacesAutocomplete apiKey="xxx" fetchDetails={true} defaultValue={where ? { label: where } : null} onLoadFailed={(error) => console.error("Google Places Autocomplete load failed", error)} selectProps={{ placeholder: "Enter suburb for the task...", sClearable: true, menuPortalTarget: document.body, value: where ? { label: where } : null, onChange: (selectedOption) => { if (selectedOption) { setWhere(selectedOption.label); } else { setWhere(''); } }, styles: { control: (provided) => ({ ...provided, height: '48px', // Slightly smaller to match NextUI "lg" more closely minHeight: '48px', borderRadius: '0.375rem', // Matches NextUI's rounded-lg borderColor: 'hsl(214, 100%, 50%)', // Primary color similar to NextUI boxShadow: 'none', '&:hover': { borderColor: 'hsl(214, 100%, 50%)', }, '&.is-focused': { borderColor: 'hsl(214, 100%, 50%)', boxShadow: '0 0 0 2px rgba(0, 111, 238, 0.2)', // Similar to NextUI focus effect }, }), singleValue: (provided) => ({ ...provided, color: 'black', }), input: (provided) => ({ ...provided, color: 'black', }), menu: (provided) => ({ ...provided, zIndex: 9999, borderRadius: '0.375rem', boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)', }), option: (provided, state) => ({ ...provided, backgroundColor: state.isSelected ? 'hsl(214, 100%, 50%)' : state.isFocused ? 'hsl(214, 100%, 95%)' : 'white', color: state.isSelected ? 'white' : 'black', ':active': { backgroundColor: 'hsl(214, 100%, 50%)', color: 'white', }, }), dropdownIndicator: (provided) => ({ ...provided, color: 'hsl(214, 20%, 50%)', // Subtle indicator color }), clearIndicator: (provided) => ({ ...provided, color: 'hsl(214, 20%, 50%)', // Subtle clear indicator color }), }, }} autocompletionRequest={{ componentRestrictions: { country: 'AU' }, types: ['(regions)'], // Add a custom filter to remove train stations and other irrelevant results strictbounds: true, }} />
解决方案
Google Places Autocomplete本身不支持直接插入自定义选项,但可以通过loadOptions方法手动把自定义选项和API返回的结果拼在一起,具体步骤如下:
替换
autocompletionRequest为loadOptions
放弃直接用autocompletionRequest配置,改用loadOptions自定义请求逻辑,手动插入自定义选项。修改组件代码
给GooglePlacesAutocomplete添加loadOptions属性,同时调整selectProps里的逻辑:
<GooglePlacesAutocomplete apiKey="xxx" fetchDetails={true} defaultValue={where ? { label: where } : null} onLoadFailed={(error) => console.error("Google Places Autocomplete load failed", error)} // 自定义加载选项逻辑 loadOptions={async (inputValue) => { // 定义自定义选项 const customOption = { label: 'Remote', value: 'Remote' }; // 输入为空时,只返回自定义选项 if (!inputValue) { return [customOption]; } // 调用Google Places API获取预测结果 const response = await fetch( `https://maps.googleapis.com/maps/api/place/autocomplete/json?input=${encodeURIComponent(inputValue)}&types=(regions)&components=country:AU&key=xxx` ); const data = await response.json(); // 格式化API返回结果,和自定义选项结构统一 const apiOptions = data.predictions.map(prediction => ({ label: prediction.description, value: prediction.description, placeId: prediction.place_id // 保留placeId,方便后续获取地点详情 })); // 把自定义选项放在第一个位置,拼接结果返回 return [customOption, ...apiOptions]; }} selectProps={{ placeholder: "Enter suburb for the task...", isClearable: true, // 注意你原代码里的`sClearable`是拼写错误,应该是`isClearable` menuPortalTarget: document.body, value: where ? { label: where } : null, onChange: (selectedOption) => { if (selectedOption) { setWhere(selectedOption.label); // 针对自定义选项做特殊处理(如果需要) if (selectedOption.value === 'Remote') { // 比如清空地点相关状态等操作 } else { // 原有的获取地点详情逻辑可以保留,用selectedOption.placeId调用API } } else { setWhere(''); } }, // 保留你原有的样式配置 styles: { // ...你的样式代码 }, }} />
- 注意事项
- 替换API请求URL里的
xxx为你的真实API Key - 修正了
selectProps里的属性拼写错误:sClearable→isClearable - 如果需要获取普通地点的详情,在
onChange里判断是否为自定义选项,再执行对应的API请求
- 替换API请求URL里的
这样就能让“Remote”选项始终出现在下拉列表的第一个位置,同时保留Google Places的正常预测功能。
内容的提问来源于stack exchange,提问作者Osman Remzi
相关产品推荐
相关产品推荐

