3

我想在我的表格中输入位置信息,如下所示

在此处输入图像描述

我正在为此使用现成的组件https://www.npmjs.com/package/react-google-places-autocomplete

import React from "react";
import GooglePlacesAutocomplete from "react-google-places-autocomplete";

const GooglePlacesAutocompleteComponent = () => (
  <div>
    <GooglePlacesAutocomplete
      apiKey="xxxxxxxxxxxxxxx"
    />
  </div>
);

export default Component;

我通常对材料 ui 使用反应钩子形式执行以下操作Textfield是:

const validationSchema = Yup.object().shape({
  location: Yup.string().required("Location is required"),
});

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

and materialui textfield

<Controller
  name="location"
  control={control}
  render={({ field: { ref, ...field } }) => (
    <TextField
      {...field}
      inputRef={ref}
      fullWidth
      label="location"
      margin="dense"
      error={errors.location ? true : false}
    />
  )}
/>
<Typography variant="inherit" color="textSecondary">
  {errors.name?.message}
</Typography>

所以在这里而不是TextField我必须使用GooglePlacesAutocompleteComponent

我希望用户知道它的要求。

我认为像下面这样的事情应该是可能的,但我没有得到什么道具可以通过:

<Controller
  name="location"
  control={control}
  render={({ field: { ref, ...field } }) => (
    <GooglePlacesAutocompleteComponent
      <--------------------------->
      But for this component how can i pass the below things
      {...field}
      inputRef={ref}
      fullWidth
      label="location"
      margin="dense"
      error={errors.location ? true : false}
      <--------------------------->
    />
  )}
/>
<Typography variant="inherit" color="textSecondary">
  {errors.name?.message}
</Typography>
4

1 回答 1

1

GooglePlacesAutocomplete在内部使用。在 RHF docs中,它向您展示了如何与Selectreact-select 中的组件集成:

<Controller
  name="iceCreamType"
  control={control}
  render={({ field }) => <Select 
    {...field} 
    options={[
      { value: "chocolate", label: "Chocolate" },
      { value: "strawberry", label: "Strawberry" },
      { value: "vanilla", label: "Vanilla" }
    ]} 
  />}
/>

GooglePlacesAutocomplete暴露一个SelectProps道具让你覆盖Select道具,所以这就是你如何在 RHF 中使用它:

const GooglePlacesAutocompleteComponent = ({ error, ...field }) => {
  return (
    <div>
      <GooglePlacesAutocomplete
        apiKey="xxxxxxxxxxxxxxx"
        selectProps={{ ...field, isClearable: true }}
      />
      {error && <div style={{ color: "red" }}>{error.message}</div>}
    </div>
  );
};

并以您的形式:

<Controller
  name="location"
  rules={{
    required: "This is a required field"
  }}
  control={control}
  render={({ field, fieldState }) => (
    <GooglePlacesAutocompleteComponent
      {...field}
      error={fieldState.error}
    />
  )}
/>

Codesandbox 演示

于 2021-10-22T05:21:16.993 回答