javascript - 使用自定义组件时,onChange 处理程序不会触发
问题描述
我在 React 应用程序中使用Formik进行验证。
验证工作正常,但我的 onChange 处理程序没有触发:
<Field
type="text"
name="name"
placeholder="First Name"
component={Input}
onChange={() => console.log("gfdg")}
/>
为什么是这样?
解决方案
在内部Input
,您订购传递给输入元素的道具的方式意味着您onChange
正在被 Formik 的onChange
. 当您Field
使用自定义组件(即Input
在您的情况下)创建 a 时,Formik 将其传递FieldProps
给组件。FieldProps
包含一个field
包含各种处理程序的属性,包括onChange
.
在你的Input
组件中你这样做(我已经删除了不相关的道具):
<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
,但也许您有一些特定的用例。
推荐阅读
- html - 如何在使用 powerflow 时将 html 转换为错误最少的单词?
- java - 错误:缺少 JavaFX 运行时组件。构建 javafx 应用程序时
- mvvm - RXSwift 结合两个 observables 并调用 API
- python - 烧瓶多个实例相同的对象访问
- mysql - 如何在 SQL 的 case 语句中添加 2 个不同的列值?
- reactjs - React js TypeError:无法读取未定义的属性“参数”。我正在使用反应路由器 ^5.2
- plyr - 如何插入两个不同的平均列,保持 R 中的第一组排序?
- oracle - Oracle 和 HTTP - 全局设置 HTTP 连接超时的任何方式
- javascript - 如何在输入字段的输入值下方显示看起来像占位符的虚线
- express - express-fileupload 中间件重写