0

Недавно начал изучать react-hook-form и столкнулся с такой проблемой. Предположим имеется отдельный компонент <Input tag='input' type='text' name='name'...../>, который возвращает input/select/checkbox в зависимости от переданных props-ов. При использовании react-hook-form обязательным является использование ref-а, но как его передать в качестве props-a? И вообще, возможен ли такой механизм или при использовании react-hook-form не предусмотрено создание input-ов с помощью отдельного компонента?

import React from 'react'
import classNames from 'classnames'
import {Button} from '../../components'
import {useForm} from 'react-hook-form'

function Order() {
    const {register, handleSubmit, errors} = useForm()

    const submitForm = (data) => {
        console.log(data)
    }

    return (
        <div>
            <form>
                {/* <input 
                        type="text"
                        name='name' 
                        placeholder='Ім`я' 
                        className={`input input__solid input__light ${errors.name ? 'input__error' : ''}`} 
                        ref={register({required: true})}
                /> */}
                    
                <Input tag="input" type='text' name='name' placeholder='Name' ref={register({required: true})} className={`${errors.name ? 'input__error' : ''}`}  solid light/>

                <Button onClick={handleSubmit(submitForm)} type="submit" solid light>Press</Button>
            </form>
       </div>
    )
}

function Input({tag, type, placeholder, name, className, ref, solid, dark, light}) {
    let outputInput = null

    if(tag === 'input'){
        outputInput = <input type={type} name={name} placeholder={placeholder} ref={ref} className={classNames('input', className, {
            'input--dark': dark,
            'input--light': light,
            'input__solid': solid,
        })}/>
    }
    // else if...

    return (
        outputInput
    )
}

1 ответ 1

0

Да передать ref возможно, ниже привожу работающий пример. А вообще данную задачу с react-hook-form можно решить больше чем двумя способами.

import React from "react";
import { useForm } from "react-hook-form";

const Order = () => {
  const { register, handleSubmit } = useForm();

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

  return (
    <form onSubmit={handleSubmit(submitForm)}>
      <Input
        tag="input"
        type="text"
        name="name"
        placeholder="Name"
        defaultValue=""
        ref={register({ required: false })}
      />
      <Input
        tag="checkbox"
        type="checkbox"
        name="checkbox"
        ref={register({ required: false })}
        label="Label for checkbox"
      />
      <button type="submit">Press</button>
    </form>
  );
};

const Input = React.forwardRef(
  ({ tag, name, label, ...restProps }, forwardedRef) => {
    switch (tag) {
      case "input":
        return <input name={name} ref={forwardedRef} {...restProps} />;
      case "checkbox":
        return (
          <div>
            <label htmlFor={name}>{label}</label>
            <input name={name} ref={forwardedRef} {...restProps} />
          </div>
        );
      default:
        return null;
    }
  }
);

export default Order;

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.