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

如何将react-google-places-autocomplete与react-hook-form集成

位置输入示例

实现步骤

1. 修改封装的地址自动补全组件

先调整原有组件的定义,支持接收react-hook-form传递的绑定参数、错误状态、ref绑定,同时适配第三方组件的返回值格式:

import React from "react";
import GooglePlacesAutocomplete from "react-google-places-autocomplete";
import { TextField } from "@mui/material"; // 复用MUI输入框保证样式统一,不需要可以删掉

const GooglePlacesAutocompleteComponent = ({
  value,
  onChange,
  error,
  label,
  inputRef,
  ...rest
}) => {
  // 适配第三方组件的返回格式:默认返回{ label: 地址文本, value: 地址详情对象 },提取地址文本存入表单
  const handlePlaceChange = (place) => {
    onChange(place ? place.label : "");
  };

  return (
    <div>
      <GooglePlacesAutocomplete
        apiKey="xxxxxxxxxxxxxxx"
        // 回显已选值
        value={value ? { label: value, value: null } : null}
        onChange={handlePlaceChange}
        // 自定义输入框样式、绑定ref、错误状态
        selectProps={{
          inputRef,
          error,
          label,
          TextFieldComponent: TextField,
          fullWidth: true,
          margin: "dense",
          ...rest
        }}
      />
    </div>
  );
};

// 修正原代码错误的导出声明
export default GooglePlacesAutocompleteComponent;

2. 替换Controller内的组件

原有表单校验逻辑不需要修改,直接把TextField替换为调整后的地址组件即可:

import GooglePlacesAutocompleteComponent from './你的组件存储路径';

// 原有validationSchema、useForm逻辑完全保留不变
const validationSchema = Yup.object().shape({
  location: Yup.string().required("Location is required"),
});

const {
  control,
  handleSubmit,
  formState: { errors },
  reset,
  setError,
} = useForm({
  resolver: yupResolver(validationSchema),
});

// 替换后的接入代码
<Controller
  name="location"
  control={control}
  render={({ field: { ref, ...field } }) => (
    <GooglePlacesAutocompleteComponent
      {...field}
      inputRef={ref}
      label="location"
      error={!!errors.location}
    />
  )}
/>
<Typography variant="inherit" color="error">
  {/* 修正原代码的字段名错误,原来的errors.name改为errors.location */}
  {errors.location?.message}
</Typography>

核心配置说明

  • 字段绑定:value和onChange由Controller的field参数自动传入,仅需在组件内做一层格式转换适配第三方组件的返回规则即可
  • ref绑定:将ref传入selectProps.inputRef绑定到真实输入框节点,满足react-hook-form的聚焦校验、自动滚动到错误字段等需求
  • 样式配置:如果不需要复用MUI样式,可以删除TextFieldComponent相关配置,自行添加CSS类覆盖第三方组件的默认样式
  • 错误状态:错误布尔值会透传给内部输入框触发错误态样式,底部Typography直接输出错误提示即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 08:39:03