首页 > 解决方案 > 我想在下拉菜单上显示标题,当有人选择一个选项并提交时,我想提交年份值

问题描述

我想在 material-ui Autocomplete 下拉菜单上显示标题,当有人选择一个选项并提交时,我希望提交年份值(注册到 RHF):

import React from "react";
import { useForm, Controller } from "react-hook-form";
import { TextField } from "@material-ui/core";
import Autocomplete from "@material-ui/lab/Autocomplete";

function App() {
  const { control, handleSubmit, register } = useForm();
  const onSubmit = (data) => console.log(data);
  const top100Films = [
    { title: "The Shawshank Redemption", value: 1994 },
    { title: "The Godfather", year: 1972 },
    { title: "The Godfather: Part II", year: 1974 }
  ];
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Autocomplete
        id="combo-box-demo"
        options={top100Films}
        getOptionLabel={(option) => option.title}
   
        style={{ width: 300 }}
        renderInput={(params) => (
          <TextField
            {...params}
            inputRef={register}
            name="formfield"
            label="Combo box"
            variant="outlined"
          />
        )}
      />

      <input type="submit" />
    </form>
  );
}

export default App;

标签: reactjsformsautocompletematerial-uireact-hook-form

解决方案


Ciao,我终于找到了解决这个问题的方法。这是代码:

import React from "react";
import "./styles.css";
import { useForm, Controller } from "react-hook-form";
import { TextField } from "@material-ui/core";
import { Autocomplete } from "@material-ui/lab";

const top100Films = [
  { _id: 1, title: "The Shawshank Redemption", year: 1994 },
  { _id: 2, title: "The Godfather", year: 1972 },
  { _id: 3, title: "The Godfather: Part II", year: 1974 }
];

export default function App() {
  const { register, handleSubmit, control } = useForm();

  const getOpObj = (option) => {
    if (!option) return option;
    if (!option._id) option = top100Films.find((op) => op._id === option);
    return option;
  };

  const onSubmit = (data) => {
    console.log(top100Films[data.film - 1].year);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Controller
        name="film"
        as={
          <Autocomplete
            options={top100Films}
            getOptionLabel={(option) => getOpObj(option).title}
            style={{ width: 300 }}
            getOptionSelected={(option, value) => {
              if (!option) return option;
              return option._id === getOpObj(value)._id;
            }}
            renderInput={(params) => (
              <TextField
                {...params}
                name="formfield"
                label="Combo box"
                variant="outlined"
              />
            )}
          />
        }
        onChange={([, obj]) => {
          const op = getOpObj(obj);
          if (op) return getOpObj(obj)._id;
          return null;
        }}
        control={control}
        defaultValue={null}
      />
      <input type="submit" />
    </form>
  );
}  

解释:

如您所见top100Films,现在包含一个附加属性_id。我需要它是因为我发现getOptionLabel,getOptionSelectedonChange. These functions sometimes receive the the option structure (and this is what we expect) and sometimes receive a value (and this value will be acceptable only if options contains an attribute called _idthat starts from 1 ).

我不知道为什么会这样。也许是与Controller结合的组件Autocomplete。可能Autocomplete包含一些错误。MaybeController仅以特定方式接受选项。我真的不知道。

所以现在提交时,您收到的数据(如果您选择例如“肖申克的救赎”)是:

{
   film: 1
}

最后,要获得year您可以做的所选元素的

top100Films[data.film - 1].year

这里是代码框示例。


推荐阅读