【问题标题】:react-hook-form onSubmit not triggeredreact-hook-form onSubmit 未触发
【发布时间】:2021-07-28 23:22:53
【问题描述】:
import React, { useState } from "react";
import FileBase64 from "react-file-base64";
import { useDispatch } from "react-redux";
import { makeStyles } from "@material-ui/core/styles";
import { TextField, Select, Input, MenuItem, Button } from "@material-ui/core";
import { useForm, Controller } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { updatePost } from "../actions/post";

const useStyles = makeStyles((theme) => ({
  textField: {
    marginBottom: theme.spacing(2),
  },
  buttons: {
    marginTop: theme.spacing(2),
  },
}));

const tags = ["fun", "programming", "health", "science"];

const postSchema = yup.object().shape({
  title: yup.string().required(),
  subtitle: yup.string().required(),
  content: yup.string().min(20).required(),
  tag: yup.mixed().oneOf(tags),
});

const EditPostForm = ({ history, post, closeEditMode }) => {
  const dispatch = useDispatch();

  const [file, setFile] = useState(post?.image);
  const { register, handleSubmit, control, errors, reset } = useForm({
    resolver: yupResolver(postSchema),
  });

  const onSubmit = (data) => {
    const updatedPost = {
      _id: post._id,
      ...data,
      image: file,
    };
    dispatch(updatePost(post._id, updatedPost));

    reset();
    setFile(null);
    closeEditMode();
  };

  const classes = useStyles();
  return (
    <div>
      <form noValidate autoComplete="off" onSubmit={handleSubmit(onSubmit)}>
        <TextField
          id="title"
          label="Başlık"
          name="title"
          variant="outlined"
          className={classes.textField}
          size="small"
          {...register('title')}
          error={errors?.title ? true : false}
          fullWidth
          defaultValue={post?.title}
        />
        <TextField
          id="subtitle"
          label="Alt Başlık"
          name="subtitle"
          variant="outlined"
          className={classes.textField}
          size="small"
          {...register('subtitle')}
          error={errors?.subtitle ? true : false}
          fullWidth
          defaultValue={post?.subtitle}
        />
          <Controller 
            render={({field}) => (
                <Select
                    {...field}
                    input={<Input />}
                    className={classes.textField}
                    fullWidth
                >
                    {
                        tags.map((tag, index) => (
                            <MenuItem {...field} key={index} value={tag}>
                                {tag}
                            </MenuItem>
                        ))
                    }
                </Select>
            )}
            name='tag'
            control={control}
            error={errors?.tag ? true : false}
            defaultValue={tags[0]}
        />
        <TextField
          id="content"
          label="İçerik"
          name="content"
          multiline
          size="small"
          {...register('content')}
          rows={16}
          className={classes.textField}
          variant="outlined"
          error={errors?.content ? true : false}
          fullWidth
          defaultValue={post?.content}
        />
        <FileBase64 multiple={false} onDone={({ base64 }) => setFile(base64)} />
        <div className={classes.buttons}>
          <Button color="primary" variant="outlined" onClick={closeEditMode}>
            Vazgeç
          </Button>{" "}
          <Button color="secondary" variant="outlined" type="submit" >
            Kaydet
          </Button>
        </div>
      </form>
    </div>
  );
};

export default EditPostForm;

我有 EditPostForm 组件,组件没有给出任何错误,但是当我尝试提交表单时,onSubmit 函数没有被触发。

我使用 react-hook-form 创建表单,并在表单内使用了 Material UI 组件。 当我单击具有提交类型的按钮时,不会触发在 handleSubmit 内部调用的 onSubmit 函数。为什么没有触发 onSubmit?

【问题讨论】:

  • 能否请您也发布您的 yup 架构?
  • 代码看起来不错,我认为您的验证有问题。在测试应用程序时,您可能为内容字段键入的字符数少于 28 个。我建议您添加一些消息以便更好地调试。

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


【解决方案1】:

onSubmit 未触发,因为您可能有表单错误

你可以从formState对象(const { formState } = useForm(...))中得到errors 然后在你的代码中使用error={formState.errors?.content ? true : false} https://react-hook-form.com/api/useform/formstate

在此处查看示例 https://codesandbox.io/s/keen-burnell-2yufj?file=/src/App.js

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-18
    • 2021-10-05
    • 2021-12-05
    • 2022-01-06
    相关资源
    最近更新 更多