简体   繁体   English

react-hook-form 在组件中用于传递动态文本字段的道具

[英]react-hook-form use in component to pass props for dynamic text fields

I have the following component我有以下组件

import React from 'react';
import PropTypes from 'prop-types';
import { useForm } from 'react-hook-form';

export default function FormField({ type, name, formRegister, errorMsg, state }) {
  const methods = useForm();
  const { register } = methods;

  return (
    <>
      <div>
        <label htmlFor={name} className="block text-sm font-medium text-gray-900">
          Password
        </label>

        <div className="mt-1">
          <input
            type={type}
            name={name}
            {...register({ formRegister }, { required: { errorMsg } })}
            className="py-3 px-4 block w-full shadow-sm text-gray-900 focus:ring-blue-700 focus:border-blue-900 border-gray-300 rounded-md"
            onChange={(event) => {state}(event.target.value)}
          />
        </div>
      </div>
    </>
  );
}

FormField.PropTypes = {
  type: PropTypes.string.isRequired,
  name: PropTypes.string.isRequired,
  formRegister: PropTypes.string.isRequired,
  errorMsg: PropTypes.string.isRequired,
  state: PropTypes.string.isRequired
};

FormField.defaultProps = {
  type: 'text',
  name: 'text',
  formRegister: 'text',
  errorMsg: 'text is required',
  state: 'setName'
};

My goal for this component is to create a dynamic field component so I can do the following我对这个组件的目标是创建一个动态字段组件,以便我可以执行以下操作

<FormField
  type="password"
  name="password"
  formRegister="password"
  errorMsg="Password is required"
  state="setPassword"
/>

However, I'm having issues in passing in the react-form-hooks ...register但是,我在传递 react-form-hooks ...register时遇到问题

I get the following我得到以下

TypeError: path.split is not a function

Any help would be great, cheers.任何帮助都会很棒,干杯。

You are passing an object to register as the first argument instead of the required string for the field name.您正在传递一个 object 来register为第一个参数,而不是字段名称所需的string Just remove the curly brackets.只需删除大括号即可。

<input
  type={type}
  {...register(name, { required: errorMsg })}
  className="py-3 px-4 block w-full shadow-sm text-gray-900 focus:ring-blue-700 focus:border-blue-900 border-gray-300 rounded-md"
/>

You could also simplify your interface by using your name prop as the first argument for your register call.您还可以通过使用name属性作为register调用的第一个参数来简化您的界面。 The spread of register will also return a name property set to the name of the first argument you pass to register . register的展开还将返回一个name属性,该属性设置为您传递给register的第一个参数的名称。

You are also overriding onChange - this is another property that the call of register will return - so you should remove it.您还覆盖了 onChange - 这是 register 调用将返回的另一个属性 - 因此您应该将其删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM