首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >未触发react-hook-form onSubmit

未触发react-hook-form onSubmit
EN

Stack Overflow用户
提问于 2021-05-06 23:45:23
回答 1查看 2.1K关注 0票数 0
代码语言:javascript
复制
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来创建我的表单,并在表单中使用了大量的UI组件。当我单击类型为submit的按钮时,不会触发在handleSubmit内部调用的onSubmit函数。为什么没有触发onSubmit?

EN

回答 1

Stack Overflow用户

发布于 2021-05-09 04:36:34

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

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

请参阅此处的示例https://codesandbox.io/s/keen-burnell-2yufj?file=/src/App.js

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67421601

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档