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

如何修复TypeScript错误:'string'无法分配给'Ref<InputRef> | undefined'

解决React+TypeScript中PlacesAutocomplete组件的TS2322错误

错误详情

编译阶段触发TypeScript错误TS2322,错误位置在places-autocomplete.tsx第12行的Input组件ref属性:

C:/Users/danie/OneDrive/Desktop/Project/seller-app/src/components/ui/maps/places-autocomplete.tsx
TypeScript error in C:/Users/danie/OneDrive/Desktop/Project/seller-app/src/components/ui/maps/places-autocomplete.tsx(12,55):
Type 'string' is not assignable to type 'Ref<InputRef> | undefined'.  TS2322

    10 |   )
    11 |   return (
> 12 |     <Input placeholder='Start typing or move the map' ref='autoCompleteRef' />
       |                                                       ^
    13 |   )
    14 | }
    15 |

错误核心:Input组件的ref属性要求接收Ref<InputRef>类型或undefined,当前传入的字符串'autoCompleteRef'类型不匹配。

原问题代码

import { Input } from "antd"
import React, { useRef } from "react"

const PlacesAutocomplete = () => {
  const autoCompleteRef = useRef(null)

  const autoComplete = new (window as any).google.maps.places.Autocomplete(
    autoCompleteRef.current,
    { types: ["(cities)"], componentRestrictions: { country: "us" } }
  )
  return (
    <Input placeholder='Start typing or move the map' ref='autoCompleteRef' />
  )
}

export default PlacesAutocomplete

修复方案

从三个核心点修正:

  • 传递正确的ref对象:直接传入useRef创建的autoCompleteRef,而非字符串
  • 指定ref的类型:导入Antd的InputRef类型,给useRef添加泛型约束
  • 延迟初始化Autocomplete:将实例创建逻辑放到useEffect中,确保组件挂载后ref已指向真实DOM元素

修正后的完整代码

import { Input, InputRef } from "antd"
import React, { useRef, useEffect } from "react"

const PlacesAutocomplete = () => {
  // 给ref指定Antd Input对应的类型
  const autoCompleteRef = useRef<InputRef>(null)

  useEffect(() => {
    // 确保ref存在且Google Maps已加载
    if (!autoCompleteRef.current || !window.google) return
    
    // Antd Input的ref需通过.input访问真实DOM元素
    const autoComplete = new window.google.maps.places.Autocomplete(
      autoCompleteRef.current.input,
      { types: ["(cities)"], componentRestrictions: { country: "us" } }
    )

    // 可选:添加组件卸载时的清理逻辑
    return () => {
      // 若需销毁Autocomplete实例,可在此处理
    }
  }, [])

  return (
    <Input placeholder='Start typing or move the map' ref={autoCompleteRef} />
  )
}

export default PlacesAutocomplete

关键说明

  • Antd的Input组件ref为InputRef类型,内部真实input DOM元素需通过.input属性获取
  • useEffect确保组件挂载后再初始化Google Places Autocomplete,避免ref.current为空的问题
  • 若Google Maps类型缺失,可执行npm install @types/google.maps添加官方类型支持

内容的提问来源于stack exchange,提问作者Daniel.M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 16:36:10