本文介绍了为什么未使用 react-hook-form 在 Material UI Autocomplete 中设置初始值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 react-hook-form(https://react-hook-form.com/) 在我的演示中.

我无法设置 AutoComplete 的默认值.我已经按照文档中的说明尝试了 defaultValue 但它不起作用.这是我的代码:

https://codesandbox.io/s/react-hook-form-get-started-v24jk

 const { register, handleSubmit, setValue } = useForm({默认值: {分辨率代码:1993}});

应选择预期输出辛德勒名单

解决方案

首先,您需要使用 react-hook-form 中的 getValues() 方法来获取表单状态的值.

const { register, handleSubmit, setValue, getValues } = useForm({默认值: {分辨率代码:1993}});

然后您的 Autocomplete,您应该设置 defaultValue 道具,以便它返回 top100Films 数组中匹配年份 (1993).

defaultValue={top100Films.find((film) => film.year === getValues().resolutionCode)}

这是对您的代码的完整更改(将您的演示与 此处):

从react"导入React;从react-dom"导入 ReactDOM;import { useForm } from "react-hook-form";从@material-ui/core"导入 { Button, TextField, Typography };从@material-ui/lab/Autocomplete"导入自动完成;const top100Films = [{标题:《肖申克的救赎》,年份:1994},{书名:《教父》,年份:1972},{标题:教父:第二部分",年份:1974},{ title: 《黑暗骑士》, 年份: 2008 },{书名:《十二怒汉》,年份:1957},{书名:《辛德勒的名单》,年份:1993}];功能应用(){const { register, handleSubmit, setValue, getValues } = useForm({默认值: {分辨率代码:1993}});React.useEffect(() => {注册({名称:分辨率代码"});});const onSubmit = 数据 =>{控制台日志(数据);};返回 (<form onSubmit={handleSubmit(onSubmit)}><自动完成选项={top100Films}getOptionLabel={option =>option.title}defaultValue={top100Films.find((film) => film.year === getValues().resolutionCode)}onChange={(e, data) =>{setValue("resolutionCode", data.year);}}renderInput={params =>{返回 (<文本字段{...参数}//inputRef={寄存器}label="{"解析码"}变体=概述"名称={分辨率代码"}defaultValue="1993"}全屏宽度值={参数}/>);}}/><div className="button-group"><按钮变体=包含"类型=提交"className="MuiButton-sizeMedium"颜色=主要"禁用海拔>登录</按钮>

</表单>);}

I am using react-hook-form(https://react-hook-form.com/) in my demo.

I am not able to set the default value of AutoComplete. I already tried defaultValue as mention in the documentation but it is not working.Here is my code:

https://codesandbox.io/s/react-hook-form-get-started-v24jk

 const { register, handleSubmit, setValue } = useForm({
    defaultValues: {
      resolutionCode: 1993
    }
  });

expected output Schindler's List value should be selected

解决方案

First, you will need to use the getValues() method from react-hook-form to get the values of the form state.

const { register, handleSubmit, setValue, getValues } = useForm({
  defaultValues: {
    resolutionCode: 1993
  }
});

Then your Autocomplete, you should set the defaultValue props such that it returns the object in the top100Films array that matches the year (1993).

defaultValue={top100Films.find((film) => film.year === getValues().resolutionCode)}

Here is the full changes to your code (forked your demo with the changes over here):

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

const top100Films = [
  { title: "The Shawshank Redemption", year: 1994 },
  { title: "The Godfather", year: 1972 },
  { title: "The Godfather: Part II", year: 1974 },
  { title: "The Dark Knight", year: 2008 },
  { title: "12 Angry Men", year: 1957 },
  { title: "Schindler's List", year: 1993 }
];
function App() {
  const { register, handleSubmit, setValue, getValues } = useForm({
    defaultValues: {
      resolutionCode: 1993
    }
  });

  React.useEffect(() => {
    register({ name: "resolutionCode" });
  });
  const onSubmit = data => {
    console.log(data);
  };
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Autocomplete
        options={top100Films}
        getOptionLabel={option => option.title}
        defaultValue={top100Films.find((film) => film.year === getValues().resolutionCode)}
        onChange={(e, data) => {
          setValue("resolutionCode", data.year);
        }}
        renderInput={params => {
          return (
            <TextField
              {...params}
              // inputRef={register}
              label={"Resolution Code"}
              variant="outlined"
              name={"resolutionCode"}
              defaultValue={"1993"}
              fullWidth
              value={params}
            />
          );
        }}
      />
      <div className="button-group">
        <Button
          variant="contained"
          type="submit"
          className="MuiButton-sizeMedium"
          color="primary"
          disableElevation
        >
          Login
        </Button>
      </div>
    </form>
  );
}

这篇关于为什么未使用 react-hook-form 在 Material UI Autocomplete 中设置初始值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 08:03