简体   繁体   English

未触发 react-hook-form onSubmit

[英]react-hook-form onSubmit not triggered

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;

I have EditPostForm component, component doesn't give any error but when I tried to submit my form onSubmit function is not triggered.我有 EditPostForm 组件,组件没有给出任何错误,但是当我尝试提交表单时,没有触发 onSubmit 函数。

I used react-hook-form to create my form and I used material UI components inside form.我使用 react-hook-form 来创建我的表单,并在表单中使用了 material UI 组件。 When I Click button which has type submit does not trigger onSubmit function which is called inside of handleSubmit.当我单击具有提交类型的按钮时,不会触发在 handleSubmit 内部调用的 onSubmit 函数。 Why onSubmit is not triggered?为什么不触发onSubmit?

onSubmit isn't triggered because you may have form errors onSubmit未触发,因为您可能有表单错误

You can get errors from formState object ( const { formState } = useForm(...) ) And then use error={formState.errors?.content? true: false}您可以从formState object ( const { formState } = useForm(...) ) 得到errors ,然后使用error={formState.errors?.content? true: false} error={formState.errors?.content? true: false} in your code https://react-hook-form.com/api/useform/formstate error={formState.errors?.content? true: false}在您的代码https://react-hook-form.com/api/useform/formstate

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

I faced the same error, the problem was that, my register were Boolean and my input was string, and since the value was not required It didn't show errors until I figure out the problem and change register from Boolean to string我遇到了同样的错误,问题是,我的寄存器是 Boolean 并且我的输入是字符串,并且由于不需要该值直到我找出问题并将寄存器从 Boolean 更改为字符串时才显示错误

You need to pass onSubmit and onError both.您需要同时传递onSubmitonError

Like this:像这样:

onPress={handleSubmit(onSubmit, onErrors)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM