使用自定义组件时不会触发 onChange 处理程序

IT技术 javascript reactjs forms onchange formik
2021-04-27 15:54:22

在 React 应用程序中使用Formik进行验证。

验证工作正常,但我的 onChange 处理程序没有触发:

  <Field
    type="text"
    name="name"
    placeholder="First Name"
    component={Input}
    onChange={() => console.log("gfdg")}
  />

沙盒链接

为什么是这样?

2个回答

在里面Input,您对传递给 input 元素的 props 进行排序的方式意味着您onChange正在被 Formik 的onChange. 当您Field使用自定义组件(即Input在您的情况下)创建 a,Formik 将其传递FieldProps给组件。FieldProps包含一个field包含各种处理程序的属性,包括onChange.

在你的Input组件中你这样做(我已经删除了不相关的props):

<input
    onChange={onChange}
    {...field}
/>

看看您自己的onChange如何被 Formik 的onChange()内部取代field为了更清楚...field,基本上是导致这种情况发生:

<input
    onChange={onChange}
    onChange={field.onChange}
    // Other props inside "field".
/>

如果您要重新排序,控制台消息现在将出现:

<input
    {...field}
    onChange={onChange}
/>

但是,现在您的输入将不起作用,因为您确实需要onChange在输入更改时立即调用 Formik以让 Formik 生效。如果您希望自定义onChange事件和您的输入都能正常工作,您可以这样做:

import React from "react";
import { color, scale } from "./variables";

const Input = React.forwardRef(
  ({ onChange, onKeyPress, placeholder, type, label, field, form }, ref) => (
    <div style={{ display: "flex", flexDirection: "column" }}>
      {label && (
        <label style={{ fontWeight: 700, marginBottom: `${scale.s2}rem` }}>
          {label}
        </label>
      )}
      <input
        {...field}
        ref={ref}
        style={{
          borderRadius: `${scale.s1}rem`,
          border: `1px solid ${color.lightGrey}`,
          padding: `${scale.s3}rem`,
          marginBottom: `${scale.s3}rem`
        }}
        onChange={changeEvent => {
          form.setFieldValue(field.name, changeEvent.target.value);
          onChange(changeEvent.target.value);
        }}
        onKeyPress={onKeyPress}
        placeholder={placeholder ? placeholder : "Type something..."}
        type={type ? type : "text"}
      />
    </div>
  )
);

export default Input;

在这里看到它的行动

虽然总的来说我不太确定你想要做什么。您的表单工作正常,您可能不需要自定义,onChange但也许您有一些特定的用例。

让我首先明确这个答案仅用于帮助目的,我确实知道这个问题已被接受,但如果上述解决方案对任何人都不起作用,我确实对我的版本对上述答案进行了一些修改

这里 onChangeText 将返回数量字段的值

  <Formik
     initialValues={{ product_id: '', quantity: '', amount: '' }}
     onSubmit={(values, actions) => {
        this.submitLogin(values);
     }}

     //some other elements ....
    <Field placeholder='No. of Quantity' name='quantity' component={CustomInputComponent}
        onChangeText={value => {
           console.warn(value); // will get value of quantity
        }}
     />
  />

在您的课程之外,您可以定义您的组件

const CustomInputComponent = ({
   onChangeText,
   field, // { name, value, onChange, onBlur }
   form: { touched, errors, isValid, handleBlur, handleChange, values, setFieldValue }, // also values, setXXXX, handleXXXX, dirty, isValid, status, etc.
   ...props
}) => {
   return (
      <Input {...field} {...props} onBlur={handleBlur(field.name)}
        onChangeText={value => {
           setFieldValue(field.name, value);
           onChangeText(value); // calling custom onChangeText
        }}
     />
   )
}