使用 Material-UI 响应钩子表单验证

时间:2021-01-20 08:04:35

标签: javascript reactjs react-hook-form

我有一个以 Material-UI 作为 UI 框架的 Next.js 项目。

我正在使用 React hooks 表单进行验证。

我的主要组件有表单,我有不同输入字段的子组件。

我的表单组件如下图:

import { Paper } from "@material-ui/core";
import React from "react";
import { makeStyles, withStyles } from "@material-ui/core/styles";
import CPTextBox from "../../components/Form/CPTextBox";
import { useForm } from "react-hook-form";

const useStyles = makeStyles((theme) => ({
  root: {
    flexGrow: 1,
    "& > *": {
      margin: theme.spacing(1),
    },
  },
  paper: {
    padding: theme.spacing(2),
    textAlign: "center",
    color: theme.palette.text.secondary,
  },
}));

function create2() {
  const classes = useStyles();
  const { control, register, handleSubmit } = useForm();
  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <Paper className={classes.paper}>
      <form onSubmit={handleSubmit(onSubmit)}>
        <CPTextBox
          attributes={{
            name: "question",
            id: "text_box_1",
            label: "Enter the Question",
            disabled: false,
            type: "",
            fullWidth: true,
            control: { control },
          }}
        />
        <input type="submit" />
      </form>
    </Paper>
  );
}

export default create;

CPTextBox 组件是这样的:


import React, { useState } from "react";
import InputLabel from "@material-ui/core/InputLabel";
import FormControl from "@material-ui/core/FormControl";
import { makeStyles, useTheme } from "@material-ui/core/styles";
import { Grid, TextField } from "@material-ui/core";
import { Controller } from "react-hook-form";

const useStyles = makeStyles((theme) => ({
  formControl: {
    // margin: theme.spacing(1),
    minWidth: 120,
    fullWidth: true,
  },
  textbox: {
    width: "100%",
  },
}));

export default function CPTextBox(props) {
  const classes = useStyles();
  return (
    <FormControl fullWidth variant="outlined" className={classes.formControl}>

      <Controller
        as={TextField}
        name={props.attributes.name}
        control={props.attributes.control}
        defaultValue=""
      />
    </FormControl>
  );
}

使用此代码,它总是给出如下所示的错误:

<块引用>

服务器错误
类型错误:无法读取未定义的属性“isReValidateOnBlur”

该错误的修复方法是什么?

2 个答案:

答案 0 :(得分:1)

attributes 中的 control 属性不应该是对象。应该是控制本身:

attributes={{
            name: "question",
            id: "text_box_1",
            label: "Enter the Question",
            disabled: false,
            type: "",
            fullWidth: true,
            control: control,
          }}

答案 1 :(得分:0)

问题是在属性中传递控制对象:

<CPTextBox
          attributes={{
            name: "question",
            id: "text_box_1",
            label: "Enter the Question",
            disabled: false,
            type: "",
            fullWidth: true,
            **control: control ,**
          }}
        />