如何在 Formik 上实现自定义 handleChange 函数?

How do I implement a custom handleChange function on Formik?

在输入元素中,handleChange 函数将从 onChange 事件接收事件对象。如何为非输入字段创建自定义 handleChange 函数,如下所示?

import React from 'react';
import { useFormik } from "formik";

const SomeForm = () =>
{
  const { handleChange, handleSubmit, values } = useFormik({
    initialValues: {
      type: `company`, name: ``,
    },
    onSubmit: values => {
      console.log(JSON.stringify(values, null, 2));
    },
  });

  return (

    <div>

      <form onSubmit={ handleSubmit }>
        <label>Type</label>
        <ul>
          <li className={ values.type === `company` && `active` }
               onClick={() => handleChange(/* some custom handle change */)} >
              Company
          </li>

          <li className={ values.type === `individual` && `active` }
               onClick={() => handleChange(/* some custom handle change */)} >
              Individual
          </li>
        </ul>

        <label>Full Name</label>

        <input type="text"
               name="name" 
               value={ value.name }
               onChange={ handleChange } />
      </form>

    </div>

  )
};

export default SomeForm;

使用 Field 组件的渲染道具模式中提供的表单对象的 setField('fieldName',value) 方法。

我认为这就是您所追求的。您可以在 field.onChange(e).

之后添加您的自定义代码
// Custom field
const MyTextField = ({ label, ...props }) => {
    const [field, meta] = useField(props);
    return (
        <>
            <input {...field} {...props}
                   onChange={e => {

                       // The original handler
                       field.onChange(e)
                       
                       // Your custom code
                       console.log('I can do something else here.')

                   }}
                   className={ meta.error && 'is-invalid'}` }  />
            {meta.touched && meta.error && (
                <div>{meta.error}</div>
            )}

        </>
    );
};

然后像这样使用它

<MyTextField name="entry" type="text" />