React Hook Form with AntD Styling

♀尐吖头ヾ 提交于 2020-02-25 06:29:08

问题


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);

回答1:


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>
  );
}



回答2:


On writing such code:

<Input
  name="subtitle"
  placeholder="Add a subtitle"
  ref={register({ required: true })}
/>

You assume that Input reference is bound to input, but that's not true.

In fact, you need to bind it to inputRef.input.

You can check it with the next code:

const App = () => {
  const inputRef = useRef();
  const inputRefHtml = useRef();

  useEffect(() => {
    console.log(inputRef.current);
    console.log(inputRefHtml.current);
  });

  return (
    <FlexBox>
      <Input ref={inputRef} />
      <input ref={inputRefHtml} />
    </FlexBox>
  );
};
# Logs
Input {props: Object, context: Object, refs: Object, updater: Object, saveClearableInput: function ()…}

<input></input>

Note that antd is a complete UI library (using 3rd party "helpers" should "turn a red light"), in particular, Form has a validator implemented, you can see a variety of examples in docs.




回答3:


In case anyone is still interested in getting close to the default styles of the Form Inputs provided by Ant, here's how I got it to work:

import { Form, Button, Input } from 'antd';
import { useForm, Controller } from 'react-hook-form';

function MyForm() {
    const { control, handleSubmit, errors, setValue } = useForm();
    const emailError = errors.email && 'Enter your email address';

    const onSubmit = data => { console.log(data) };

    const EmailInput = (
        <Form.Item>
            <Input
                type="email"
                placeholder="Email"
                onChange={e => setValue('email', e.target.value, true)}
                onBlur={e => setValue('email', e.target.value, true)}
            />
        </Form.Item>
    );


    return (
        <form onSubmit={handleSubmit(onSubmit)}>
            <Controller 
                as={EmailInput} 
                name="email" 
                control={control} 
                defaultValue=""
                rules={{
                    required: true
                }}
                validateStatus={emailError ? 'error' : ''}
                help={emailError}
            />

            <Button block type="primary" htmlType="submit">
                Submit
            </Button>
        </form>
    );
}

Codesandbox sample



来源:https://stackoverflow.com/questions/58703615/react-hook-form-with-antd-styling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!