简体   繁体   English

使用 react-select 作为必填字段的 React 钩子表单

[英]React hook form with react-select as required field

I'm trying to validate a react-select input field with react-hook-form.(Required input) But I can't seem to do this with the code block below.我正在尝试使用 react-hook-form 验证 react-select 输入字段。(必需输入)但我似乎无法使用下面的代码块执行此操作。 Can anyone point me in the right direction?谁能指出我正确的方向?

<Controller
   as={Select}
   options={statusOptions}
   name="status"
   control={control}
   className="infoItemDropdown"
   rules={{ required: true }}
   styles={customStyles}
/>

You can wrapper the component react-select:您可以包装组件 react-select:

import Select from 'react-select';
import React, { useState } from 'react';
import PropTypes from 'prop-types';

const RenderSelect = (props) => {
  const {
    field: {
      value,
      onChange,
    },
    data,
  } = props;

  const [selectedOption, setSelectedOption] = useState();
  const handleChange = (e) => {
    onChange(e.value);
    setSelectedOption(e);
  };

  return (
    <Select
      value={selectedOption}
      onChange={handleChange}
      options={data}
    />
  );
};
RenderSelect.propTypes = {
  data: PropTypes.arrayOf(
    PropTypes.shape({
      value: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.number,
      ]).isRequired,
      label: PropTypes.string.isRequired,
    }),
  ).isRequired,
  field: PropTypes.shape({
    value: PropTypes.oneOfType([
      PropTypes.string.isRequired,
      PropTypes.number.isRequired,
    ]),
    onChange: PropTypes.func.isRequired,
  }),
};

RenderSelect.defaultProps = {
  field: { onChange: () => {}, value: '' },
};

export default RenderSelect;

And use it in react hook form:并以反应钩子形式使用它:

export default function MyForm() {
  const {
    handleSubmit,
    formState: { isValid },
    control,
  } = useForm({ mode: 'onChange' });

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

  const data = [
    { value: 'chocolate', label: 'Chocolate' },
    { value: 'strawberry', label: 'Strawberry' },
    { value: 'vanilla', label: 'Vanilla' },
  ];
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Controller
        name="select_something"
        control={control}
        rules={{ required: true }}
        render={({ field }) => (<RenderSelect field={field} data={data}/>)
        }
      />
      <button
        disabled={!isValid}
        type="submit"
      >
        Save
      </button>
    </form>
  );
}

This way disable the button submit if the select not has a value.如果 select 没有值,这种方式禁用按钮提交。

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

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