简体   繁体   English

自定义 onChange 事件 Formik

[英]Custom onChange event Formik

I'm trying to customize the onChange in formik input to convert the value that is string to number, however, the behavior is not changed, the console.log is also not shown on screen.我正在尝试自定义 formik 输入中的 onChange 以将字符串值转换为数字,但是,行为没有改变,console.log 也没有显示在屏幕上。 I believe it is not overwriting Formik's default behavior.我相信它不会覆盖 Formik 的默认行为。 What am I doing wrong?我究竟做错了什么?

Control Input控制输入

<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>

My Custom Component Input我的自定义组件输入

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}
    />
  )
}

I cannot reproduce your code to test it, but I suggest you try this我无法重现你的代码来测试它,但我建议你试试这个

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

instead of代替

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

You can try something like that:你可以尝试这样的事情:

  const onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    let newEvent = event;

    newEvent.target.value = "asd";
    return field.onChange(newEvent);
  };

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

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