在Input 内部,您订购传递给输入元素的道具的方式意味着您的onChange 将被Formik 的onChange 覆盖。当您使用自定义组件创建Field(即您的情况下为Input)时,Formik 将其FieldProps 传递给组件。 FieldProps 包含一个属性 field,其中包含各种处理程序,包括 onChange。
在你的Input 组件中你这样做(我已经删除了不相关的道具):
<input
onChange={onChange}
{...field}
/>
看看你自己的onChange 将如何被Formik 的onChange() 替换为field 内的field?为了更清楚...field 基本上是导致这种情况发生:
<input
onChange={onChange}
onChange={field.onChange}
// Other props inside "field".
/>
如果您要对它们重新排序,现在将显示控制台消息:
<input
{...field}
onChange={onChange}
/>
但是现在您的输入现在不起作用,因为您确实需要在输入更改时立即调用 Formik 的 onChange 以让 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;
See it here in action.
虽然总的来说我不太确定你想要做什么。您的表单工作正常,您可能不需要自定义 onChange,但也许您有一些特定的用例。