繁体   English   中英

在 react-imask、react-bootstrap 和 react-hook-form 之间共享引用

[英]Sharing refs between react-imask, react-bootstrap, and react-hook-form

我目前正在使用react-bootstrapreact-imask一起使用他们的示例和 IMaskMixin:

import { IMaskMixin } from 'react-imask';
import { FormControl } from 'react-bootstrap';

const MaskedFormControl = IMaskMixin(({inputRef, ...props}) => (
  <FormControl
    {...props}
    ref={inputRef} 
  />
));

现在,我想在这个控件中使用react-hook-form

const { register } = useForm();
<MaskedFormControl {...register('name')} />

寄存器 function 上的点差相当于此

const { onChange, onBlur, name, ref } = register('name');

所以它期望 ref 访问输入 ref,react-hook-form 中的值永远不会设置为输入中键入的内容。

我在不使用 react-hook-form 的地方使用 MasedFormControl,所以我想让它在有或没有 react-hook-form 的情况下都能工作。

我如何使这项工作?

不是特别针对 Bootstrap,但我将展示如何将 react-imask、react-hook-form 与任何类型的输入集成的一般概念:

  1. 定义模式
  const schema = yup.object({
    phone: yup
      .string()
      .required('Phone is required')
      .length(10, 'Phone must contain 10 digits'),
  });
  1. 申报表
  const { control, handleSubmit } = useForm({
    resolver: yupResolver(schema),
    mode: 'onTouched',
    defaultValues: {
      phone: "4437787349",
    },
  });
  1. 添加掩码
  const mask = useIMask({
    mask: '(000) 000-00-00',
  });
  1. 渲染输入组件
  <Controller
    render={(params) => (
      <input
        name={params.field.name}
        onBlur={params.field.onBlur}
        defaultValue={params.field.value}
        ref={mask.ref}
        onChange={() =>
          params.field.onChange({
            target: { value: mask.unmaskedValue },
          })
        }
        placeholder="Phone number"
      />
      // show error messages
      // <p>{params.fieldState.error?.message}</p>
    )}
    name="phone"
    control={control}
  />

暂无
暂无

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

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