React Hook Form 与 A​​ntD 样式 [英] React Hook Form with AntD Styling

查看:40
本文介绍了React Hook Form 与 A​​ntD 样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究如何在 antd 前端使用 react-hook-form.

我制作了这个表单,它似乎可以工作(它是多部分表单向导的第 1 部分),只是不显示错误消息.

谁能看到我在合并这两个表单系统时做错了什么?

我没有收到任何错误,但我想我已经要求两个表单字段都是必需的,但是如果我在没有完成它们的情况下按提交,则不会显示错误消息.

从react"导入React;从react-hook-form"导入 useForm;import { BrowserRouter as Router, Route } from "react-router-dom";import { StateMachineProvider, createStore } from "little-state-machine";import { withRouter } from "react-router-dom";import { useStateMachine } from "little-state-machine";从./updateAction"导入更新操作;从'antd'导入{按钮、表单、输入、分隔符、布局、排版、骨架、开关、卡片、图标、头像};const { 内容 } = 布局const { 文字,段落 } = 排版;const { 元 } = 卡;创建商店({数据: {}});const General = props =>{const { 注册,handleSubmit,错误 } = useForm();const { action } = useStateMachine(updateAction);const onSubit = 数据 =>{动作(数据);props.history.push("./ProposalMethod");};返回 (<div><内容风格={{背景:'#fff',填充:24,边距:自动",最小高度:280,宽度:'70%'}}><表单 onSubmit={handleSubmit(onSubit)}><h2>第1部分:一般</h2><Form.Item label="Title" ><输入名称=标题"placeholder="添加标题"ref={register({ required: true })}/>{errors.title &&'标题是必需的.'}</Form.Item><Form.Item label="副标题" ><输入名称=字幕"placeholder="添加副标题"ref={register({ required: true })}/>{errors.subtitle &&'需要一个副标题.'}</Form.Item><表单.项目><Button type="secondary" htmlType="submit">下一个</按钮></Form.Item></表格></内容>

);};导出默认 withRouter(General);

解决方案

react-hook-form author here.Antd Input 组件并没有真正暴露内部的ref,所以你必须在useEffect 期间register,并在onChange 期间更新值,例如:

const { register, setValue } = useForm();useEffect(() => {register({ name: 'yourField' }, { required: true });}, [])<输入名称="yourField" onChange={(e) =>setValue('yourField', e.target.value)}

我已经构建了一个包装组件来使 antd 组件集成更容易:https://github.com/react-hook-form/react-hook-form-input

从'react'导入React;从'react-hook-form'导入useForm;从'react-hook-form-input'导入{RHFInput};导入从反应选择"中选择;常量选项 = [{价值:'巧克力',标签:'巧克力'},{值:'草莓',标签:'草莓'},{价值:'香草',标签:'香草'},];功能应用(){const { handleSubmit, register, setValue, reset } = useForm();返回 (<form onSubmit={handleSubmit(data => console.log(data))}><RHF输入as={<选择选项={选项}/>}规则={{ 要求:真}}名称=反应选择"注册={注册}设置值={设置值}/><按钮类型=按钮"onClick={() =>{重启({反应选择:'',});}}>重置表格<按钮>提交</表单>);}

I'm trying to figure out how to use react-hook-form with antd front end.

I have made this form and it seems to be working (it's part 1 of a multipart form wizard) except that the error messages do not display.

Can anyone see what I've done wrong in merging these two form systems?

I'm not getting any errors, but I think I have asked for both form fields to be required but if I press submit without completing them the error messages are not displayed.

import React from "react";
import useForm from "react-hook-form";
import { BrowserRouter as Router, Route } from "react-router-dom";
import { StateMachineProvider, createStore } from "little-state-machine";
import { withRouter } from "react-router-dom";
import { useStateMachine } from "little-state-machine";

import updateAction from "./updateAction";
import { Button, Form, Input,  Divider, Layout, Typography, Skeleton, Switch, Card, Icon, Avatar } from 'antd';


const { Content } = Layout 
const { Text, Paragraph } = Typography;
const { Meta } = Card;

createStore({
  data: {}
});

const General = props => {
  const { register, handleSubmit, errors } = useForm();
  const { action } = useStateMachine(updateAction);
  const onSubit = data => {
    action(data);
    props.history.push("./ProposalMethod");
  };


  return (

      <div>

        <Content
          style={{
            background: '#fff',
            padding: 24,
            margin: "auto",
            minHeight: 280,
            width: '70%'
          }}
        >
        <Form onSubmit={handleSubmit(onSubit)}>

          <h2>Part 1: General</h2>
            <Form.Item label="Title" >
              <Input 
                name="title" 
                placeholder="Add a title" 
                ref={register({ required: true })} 
              />
              {errors.title && 'A title is required.'}
            </Form.Item>
            <Form.Item label="Subtitle" >
              <Input 
                name="subtitle" 
                placeholder="Add a subtitle" 
                ref={register({ required: true })} 
              />
              {errors.subtitle && 'A subtitle is required.'}
            </Form.Item>
            <Form.Item>
              <Button type="secondary" htmlType="submit">
                Next
              </Button>
            </Form.Item>

        </Form>

        </Content>
      </div>  
  );
};

export default withRouter(General);

解决方案

react-hook-form author here. Antd Input component doesn't really expose inner ref, so you will have to register during useEffect, and update value during onChange, eg:

const { register, setValue } = useForm();

useEffect(() => {
  register({ name: 'yourField' }, { required: true });
}, [])

<Input name="yourField" onChange={(e) => setValue('yourField', e.target.value)}

i have built a wrapper component to make antd component integration easier: https://github.com/react-hook-form/react-hook-form-input

import React from 'react';
import useForm from 'react-hook-form';
import { RHFInput } from 'react-hook-form-input';
import Select from 'react-select';

const options = [
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
  { value: 'vanilla', label: 'Vanilla' },
];

function App() {
  const { handleSubmit, register, setValue, reset } = useForm();

  return (
    <form onSubmit={handleSubmit(data => console.log(data))}>
      <RHFInput
        as={<Select options={options} />}
        rules={{ required: true }}
        name="reactSelect"
        register={register}
        setValue={setValue}
      />
      <button
        type="button"
        onClick={() => {
          reset({
            reactSelect: '',
          });
        }}
      >
        Reset Form
      </button>
      <button>submit</button>
    </form>
  );
}

这篇关于React Hook Form 与 A​​ntD 样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆