Inside Input
,您对传递给输入元素的 props 进行排序的方式意味着您的onChange
正在被 Formik 覆盖onChange
。当您创建一个Field
使用自定义组件(即Input
在你的情况下),福米克通过了它FieldProps
到组件。FieldProps
包含一个属性field
包含各种处理程序,包括onChange
.
In your Input
你这样做的组件(我已经删除了不相关的道具):
<input
onChange={onChange}
{...field}
/>
看看你自己的怎么样onChange
将被 Formik 取代onChange()
inside field
?为了更清楚...field
基本上导致这种情况发生:
<input
onChange={onChange}
onChange={field.onChange}
// Other props inside "field".
/>
如果您要重新排序,控制台消息现在将出现:
<input
{...field}
onChange={onChange}
/>
但是现在您的输入将不起作用,因为您确实需要调用 Formik'sonChange
当您的输入发生变化时,让 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;
在这里查看实际效果 https://codesandbox.io/s/j7ljpjm6v.
虽然总的来说我不太确定你想做什么。您的表单工作正常,您可能不需要自定义onChange
但也许您有一些特定的用例。