javascript - react-hook-form onSubmit 未触发

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

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 没有被触发?

最佳答案

onSubmit未触发,因为您可能有表单错误
您可以获得errors来自 formState对象 (const { formState } = useForm(...))
然后使用 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

关于javascript - react-hook-form onSubmit 未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67421601/

相关文章:

javascript - 将 XML 文件作为 JSON 加载到 NodeJS 中

css - Material-UI:背景上方的文本不透明

reactjs - 使用react-redux触发事件操作

reactjs - 将 Create-React-App 与 Material UI 结合使用

javascript - 我的函数中未调用异步 Mocha 完成()

javascript - 在 Javascript 中转换特定日期

javascript - 如何在 vue.js 中获取点击项的文本值?

reactjs - 如果我在 React 的 useEffect 第二个参数中添加多个依赖项会怎样?

css - 内联样式 react 元素宽度

javascript - React 协调中的令人惊讶的行为。为什么状态没有被重置?