将material-ui中的<TextField />组件与react-hook-form一起使用会显示警告

时间:2020-03-12 05:12:49

标签: reactjs material-ui react-hook-form

我在应用程序中使用react-hook-form进行表单状态管理。当我将<Input />用作控件时,它可以按预期方式工作,但是使用<TextField />时,它显示一条警告,指出“组件正在更改要控制的文本类型的不受控制的输入”。 这是怎么了此组件还有其他选择吗?

这是我的反应代码:

import React from "react";
import "./styles.css";
import { useForm, Controller } from "react-hook-form";
import Joi from "@hapi/joi";
import { TextField, createMuiTheme, ThemeProvider } from "@material-ui/core";

const validationSchema = Joi.object({
  username: Joi.string()
    .alphanum()
    .min(3)
    .max(30)
    .required()
});

const theme = createMuiTheme({
  palette: {
    type: "dark"
  }
});

const resolver = (data, validationContext) => {
  const { error, value: values } = validationSchema.validate(data, {
    abortEarly: false
  });

  return {
    values: error ? {} : values,
    errors: error
      ? error.details.reduce((previous, currentError) => {
          return {
            ...previous,
            [currentError.path[0]]: currentError
          };
        }, {})
      : {}
  };
};

export default function App() {
  const { register, handleSubmit, errors, control } = useForm({
    validationResolver: resolver,
    validationContext: { test: "test" }
  });

  console.log("error", errors);

  return (
    <ThemeProvider theme={theme}>
      <div className="App">
        <h1>Hello CodeSandbox</h1>

        <form onSubmit={handleSubmit(d => console.log(d))}>
          <label>Username</label>
          <Controller as={<input />} name="username" control={control} />
          <Controller
            as={<TextField />}
            name="firstName"
            label="First Name"
            control={control}
          />
          <input type="submit" />
        </form>
      </div>
    </ThemeProvider>
  );
}

,这是沙箱中的链接:https://codesandbox.io/s/react-hook-form-validationresolver-7k33n

1 个答案:

答案 0 :(得分:2)

您可以通过为输入元素提供默认值来纠正警告,以防止最初未定义它们:

 <Controller
  as={<input />}
  name="username"
  control={control}
  defaultValue=""
/>
<Controller
  as={<TextField />}
  name="firstName"
  label="First Name"
  control={control}
  defaultValue=""
/>