在formik和formik-antd中使用react-input-mask [英] Using react-input-mask with formik and formik-antd

查看:132
本文介绍了在formik和formik-antd中使用react-input-mask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将formik@jbuschke/formik-antd一起使用.我需要对输入应用掩码+7 (___) ___-__-__,所以我想使用react-input-mask.

同时,我需要解析值并删除除+和数字之外的符号,因此我自己处理onChangesetFieldValue.我可以在控制台日志中得到changedValue,但是在提交时我得到的是初始值,而不是更改后的值.

这是我的代码和演示:

const CustomInput = props => (
  <InputMask {...props}>{inputProps => <Input {...inputProps} />}</InputMask>
);

const CloseForm = () => (
  <Formik
    initialValues={{ phone: "" }}
    onSubmit={(values, { setSubmitting }) => {
      setTimeout(() => {
        alert(JSON.stringify(values, null, 2));
        setSubmitting(false);
      }, 400);
    }}
    validate={handleValidate}
  >
    {({ isSubmitting, values, setFieldValue }) => {
      return (
        <Form>
          <FormItem name="phone" label="Phone" required="true">
            <CustomInput
              mask="+7 (999) 999-99-99"
              name="phone"
              onChange={e => {
                const value = e.target.value || "";
                const changedValue = value
                  .replace(/\)/g, "")
                  .replace(/\(/g, "")
                  .replace(/-/g, "")
                  .replace(/ /g, "");
                console.log({ value });
                console.log({ changedValue });
                setFieldValue("phone", value);
              }}
            />
          </FormItem>
          <SubmitButton type="primary" disabled={isSubmitting}>
            Submit
          </SubmitButton>
          <pre>{JSON.stringify(values, null, 2)}</pre>
        </Form>
      );
    }}
  </Formik>
);

如何解决?

解决方案

问题是您解析了该值,但没有在任何地方更新它,因此changedValue在作用域的末尾消失.

将解析移至onSubmit回调,不仅您在每个渲染上都进行了不必要的解析,而且解析状态也不需要其他状态.

提示:使用单个regex表达式,不需要那么多替换.

 const CloseForm = () => (
  <Formik
    initialValues={{ phone: '' }}
    onSubmit={(value, { setSubmitting }) => {
      const changedValue = value.phone
        .replace(/\)/g, '')
        .replace(/\(/g, '')
        .replace(/-/g, '')
        .replace(/ /g, '');

      setTimeout(() => {
        alert(JSON.stringify(changedValue, null, 2));
        setSubmitting(false);
      }, 400);
    }}
    validate={handleValidate}
  >
    {({ isSubmitting, values, setFieldValue }) => {
      return (
        <Form>
          <FormItem name="phone" label="Phone" required="true">
            <CustomInput
              mask="+7 (999) 999-99-99"
              name="phone"
              onChange={e => {
                const value = e.target.value || '';
                console.log({ value });
                setFieldValue('phone', value);
              }}
            />
          </FormItem>
          <SubmitButton type="primary" disabled={isSubmitting}>
            Submit
          </SubmitButton>
          <pre>{JSON.stringify(values, null, 2)}</pre>
        </Form>
      );
    }}
  </Formik>
);
 

I'm using formik with @jbuschke/formik-antd. I need to apply a mask +7 (___) ___-__-__ to an input, so I would like to use react-input-mask.

At the same time I need to parse the value and remove symbols except + and digits, so I handle onChange and setFieldValue myself. I can get changedValue in the console log, but on submit I'm getting the initial value, not the changed one.

Here is my code and the demo:

const CustomInput = props => (
  <InputMask {...props}>{inputProps => <Input {...inputProps} />}</InputMask>
);

const CloseForm = () => (
  <Formik
    initialValues={{ phone: "" }}
    onSubmit={(values, { setSubmitting }) => {
      setTimeout(() => {
        alert(JSON.stringify(values, null, 2));
        setSubmitting(false);
      }, 400);
    }}
    validate={handleValidate}
  >
    {({ isSubmitting, values, setFieldValue }) => {
      return (
        <Form>
          <FormItem name="phone" label="Phone" required="true">
            <CustomInput
              mask="+7 (999) 999-99-99"
              name="phone"
              onChange={e => {
                const value = e.target.value || "";
                const changedValue = value
                  .replace(/\)/g, "")
                  .replace(/\(/g, "")
                  .replace(/-/g, "")
                  .replace(/ /g, "");
                console.log({ value });
                console.log({ changedValue });
                setFieldValue("phone", value);
              }}
            />
          </FormItem>
          <SubmitButton type="primary" disabled={isSubmitting}>
            Submit
          </SubmitButton>
          <pre>{JSON.stringify(values, null, 2)}</pre>
        </Form>
      );
    }}
  </Formik>
);

How can it be fixed?

解决方案

The problem is that you parsing the value but you don't update it anywhere, so changedValue dies at the end of the scope.

Move the parsing to onSubmit callback, not only you making unnecessary parsing on every render but also you won't be needed another state for the parsing value.

Hint: use a single regex expression, no need so many replaces.

const CloseForm = () => (
  <Formik
    initialValues={{ phone: '' }}
    onSubmit={(value, { setSubmitting }) => {
      const changedValue = value.phone
        .replace(/\)/g, '')
        .replace(/\(/g, '')
        .replace(/-/g, '')
        .replace(/ /g, '');

      setTimeout(() => {
        alert(JSON.stringify(changedValue, null, 2));
        setSubmitting(false);
      }, 400);
    }}
    validate={handleValidate}
  >
    {({ isSubmitting, values, setFieldValue }) => {
      return (
        <Form>
          <FormItem name="phone" label="Phone" required="true">
            <CustomInput
              mask="+7 (999) 999-99-99"
              name="phone"
              onChange={e => {
                const value = e.target.value || '';
                console.log({ value });
                setFieldValue('phone', value);
              }}
            />
          </FormItem>
          <SubmitButton type="primary" disabled={isSubmitting}>
            Submit
          </SubmitButton>
          <pre>{JSON.stringify(values, null, 2)}</pre>
        </Form>
      );
    }}
  </Formik>
);

这篇关于在formik和formik-antd中使用react-input-mask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆