使用 Controller 的 React Hook Form,是的和 Material UI - 验证问题

React Hook Form using Controller, yup and Material UI - validation issue

我有一个简单的表单,在 React Hook 表单中只有一个 Material UI TextField。我使用 Yup 模式验证(通过 yupResolver)。我尝试以视觉方式验证表单并显示错误(TextField 中的布尔属性 'error')。我将 Controller 与 'render' 道具一起使用,但是它无法在 TextField 更改时更新错误。有谁知道我在这里做错了什么?

Link to codesandbox

import React from "react";
import ReactDOM from "react-dom";
import { TextField } from "@material-ui/core";
import { Controller, useForm } from "react-hook-form";
import * as yup from "yup";

import { yupResolver } from "@hookform/resolvers/yup";
import "./styles.css";

const schema = yup.object().shape({
  title: yup.string().required("Required")
});

function App() {
  const {
    handleSubmit,
    formState: { errors },
    control
  } = useForm({
    resolver: yupResolver(schema)
  });

  const onSubmit = (data) => console.log("onSubmit", data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Controller
        render={({ formState, fieldState }) => {
          return <TextField label="Title" error={!!formState.errors?.title} />; 
        }}
        name="title"
        control={control}
      />
      <input type="submit" />
    </form>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

此外 'fieldState' 在 Controller 中似乎一直是一个空对象。它不应该显示中列出的属性吗 Link

您没有连接 material-ui 组件到 react-hook-form,您应该检查 Integrating Controlled Inputs react-hook-form 文档部分。

我按照@damjtoh 的建议找到了答案。我注意到 RHF 代码示例中的渲染函数中有一个 'field' 参数。将它添加到 TextField 与表单连接的组件。请记住添加 'defaultValue' 以避免 'changing uncontrolled input' 错误。它应该是这样的:

<form onSubmit={handleSubmit(onSubmit)}>
    <Controller
    render={({ field, formState }) => (
        <TextField
        {...field}
        label="Title"
        error={!!formState.errors?.title}
        />
    )}
    name="title"
    control={control}
    defaultValue=""
    />
    <input type="submit" />
</form>