【问题标题】:Custom onChange event Formik自定义 onChange 事件 Formik
【发布时间】:2021-10-26 12:01:20
【问题描述】:

我正在尝试自定义 formik 输入中的 onChange 以将字符串值转换为数字,但是,行为没有改变,console.log 也没有显示在屏幕上。我相信它不会覆盖 Formik 的默认行为。我做错了什么?

控制输入

<App.FormField name={'monthly_salary'}>
                      {({field, form}) => (
                        <C.InputGroup>
                          <C.InputLeftAddon bg={'primary.100'}>
                            {'R$'}
                          </C.InputLeftAddon>

                          <Custom.Input
                            variant={'secondary'}
                            placeholder={t('form.placeholder_value_zero')}
                            mask={'currency'}
                            handleChange={(e) => {
                              console.log(parseValue(e.currentTarget.value))
                              form.setFieldValue(
                                field.name,
                                parseValue(e.currentTarget.value)
                              )
                            }}
                            {...field}
                          />
                        </C.InputGroup>
                      )}
                    </App.FormField>

我的自定义组件输入

export const Input = ({mask, handleChange, ...props}: InputProps) => {
  const handleInput = useCallback(
    (e: React.FormEvent<HTMLInputElement>) => {
      if (mask === 'currency') {
        currency(e)
      }
    },
    [mask]
  )

  return (
    <C.Input
      inputMode={'numeric'}
      onInput={handleInput}
      onChange={handleChange}
      {...props}
    />
  )
}

【问题讨论】:

    标签: javascript reactjs forms formik


    【解决方案1】:

    我无法重现你的代码来测试它,但我建议你试试这个

    onChange={(e) => {
      handleChange(e);
      console.log(parseInt(e.currentTarget.value))
      form.setFieldValue(
        field.name,
        parseInt(e.currentTarget.value)
      )
    }}
    

    而不是

    handleChange={(e) => {
      console.log(parseValue(e.currentTarget.value))
      form.setFieldValue(
        field.name,
        parseValue(e.currentTarget.value)
      )
    }}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-22
      • 2018-07-06
      • 2019-11-20
      • 1970-01-01
      • 1970-01-01
      • 2020-11-09
      • 2016-07-22
      相关资源
      最近更新 更多