0

我 在我的演示中使用react-hook-formhttps://react-hook-form.com/ )。

我无法设置的默认值AutoComplete。我已经尝试过defaultValue文档中提到的,但它不起作用。这是我的代码:

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

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

应选择预期输出辛德勒的列表值

4

1 回答 1

2

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

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

然后Autocomplete,您应该设置defaultValue道具,使其返回top100Films数组中与年份(1993 年)匹配的对象。

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

这是对您的代码的全部更改(将您的演示与此处的更改分叉):

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>
  );
}
于 2020-02-07T04:39:38.290 回答