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

React中如何为Map生成的动态子组件创建Ref?(Google Autocomplete场景)

为Map生成的动态Autocomplete子组件创建Ref并获取值的解决方案

核心思路

  1. 用Ref数组管理所有动态生成的路点输入框Ref
  2. 借助Autocomplete组件的onPlaceChanged事件(而非input的onChange)获取用户选中的自动补全结果,解决推荐选项点击后值不保存的问题

具体实现步骤

1. 初始化Ref数组和状态

import { useRef, useState } from 'react';
import { Autocomplete } from '@react-google-maps/api';
import { FaPlus } from 'react-icons/fa';

// 初始化路点状态,每个元素对应输入框的值
const [wayPoints, setWayPoints] = useState([]);
// 创建Ref数组,存储每个路点输入框的Ref
const waypointRefs = useRef([]);
// 起点和终点的独立Ref
const originRef = useRef(null);
const destinationRef = useRef(null);

2. 编写添加路点的函数

const addNewStop = () => {
  // 往路点数组添加空值,触发渲染新的输入框
  setWayPoints(prev => [...prev, '']);
  // 新输入框自动获取焦点(可选)
  setTimeout(() => {
    const lastIndex = waypointRefs.current.length - 1;
    waypointRefs.current[lastIndex]?.focus();
  }, 0);
};

3. 处理Autocomplete的地点选择事件

const handleWaypointPlaceChanged = (index, autocomplete) => {
  // 获取选中的地点对象
  const place = autocomplete.getPlace();
  if (place?.formatted_address) {
    // 更新对应索引的路点状态
    setWayPoints(prev => {
      const newWayPoints = [...prev];
      newWayPoints[index] = place.formatted_address;
      return newWayPoints;
    });
    // 同步更新输入框显示值
    waypointRefs.current[index].value = place.formatted_address;
  }
};

// 起点和终点的地点选择处理
const handleOriginPlaceChanged = (autocomplete) => {
  const place = autocomplete.getPlace();
  if (place?.formatted_address) {
    originRef.current.value = place.formatted_address;
  }
};

const handleDestinationPlaceChanged = (autocomplete) => {
  const place = autocomplete.getPlace();
  if (place?.formatted_address) {
    destinationRef.current.value = place.formatted_address;
  }
};

4. 渲染动态路点组件并绑定Ref

<div className={style.form}>
  <Autocomplete onPlaceChanged={(autocomplete) => handleOriginPlaceChanged(autocomplete)}>
    <input 
      type="text" 
      id="origin" 
      ref={originRef} 
      placeholder="Enter Starting Location"
    />
  </Autocomplete>

  {wayPoints.map((input, index) => {
    return (
      <Autocomplete 
        key={index} 
        onPlaceChanged={(autocomplete) => handleWaypointPlaceChanged(index, autocomplete)}
      >
        <input 
          type="text" 
          placeholder="Enter Stop"
          // 绑定对应索引的Ref
          ref={el => waypointRefs.current[index] = el}
        />
      </Autocomplete>
    );
  })}

  <Autocomplete onPlaceChanged={(autocomplete) => handleDestinationPlaceChanged(autocomplete)}>
    <input 
      type="text" 
      id="destination" 
      ref={destinationRef} 
      placeholder="Enter Ending Location"
    />
  </Autocomplete>

  <div className={style.add} onClick={addNewStop}>
    <FaPlus/>
  </div>
</div>

关键说明

  • Ref数组绑定方式:用ref={el => waypointRefs.current[index] = el}确保每个动态输入框对应Ref数组的正确索引,避免组件复用导致的Ref错位。
  • onPlaceChanged的必要性:Google Autocomplete推荐选项被点击时,input的onChange不会触发,必须通过组件自身的onPlaceChanged事件获取选中地点,这是解决值不保存问题的核心。
  • 状态与Ref同步:路点值会实时存入wayPoints状态数组,后续可直接用该数组提交或处理数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 08:11:27