Formik handleBlur 用例
Formik handleBlur use case
handleBlur
有哪些用例?由于您可以通过 touched
对象访问触摸字段。
来自 Formik 文档:
handleBlur: (e: any) => void
onBlur
事件处理程序。当您需要跟踪输入是否为 touched
时很有用。这应该传递给 <input onBlur={handleBlur} ... />
handleBlur 是实际更新触摸的方式(或至少是其中一种方式)。如果您的输入未通过连接到 Formik 状态的 onBlur 处理程序,则不会更新触摸状态。
这是一个说明行为的代码和框:https://codesandbox.io/s/magical-gates-4cq5k?file=/src/App.js
如果您对第一个输入进行模糊处理,则 touched 会更新。如果您模糊第二个输入,触摸不会更新。第三个输入使用 useField
,这导致 onBlur
字段自动传递到我的输入。这通常是我喜欢使用 Formik(或几乎任何其他 React 表单库)的方式,因为它减少了将表单字段连接到表单状态所需的样板文件。
import React from "react";
import { Formik, Form, useField } from "formik";
import "./styles.css";
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<Formik
initialValues={{ usingUseField: "", withBlur: "", withoutBlur: "" }}
>
{({ handleChange, handleBlur, values, touched }) => {
return (
<Form>
{JSON.stringify(touched)}
<div>
<label>
With Blur
<input
onBlur={handleBlur("withBlur")}
onChange={handleChange("withBlur")}
value={values.withBlur}
/>
</label>
</div>
<div>
<label>
Without Blur
<input
onChange={handleChange("withoutBlur")}
value={values.withoutBlur}
/>
</label>
</div>
<InputUsingUseField name="usingUseField" label="Using useField" />
</Form>
);
}}
</Formik>
</div>
);
}
function InputUsingUseField({ label, name }) {
const [props] = useField(name);
return (
<div>
<label>
{label}
<input {...props} />
</label>
</div>
);
}
handleBlur
有哪些用例?由于您可以通过 touched
对象访问触摸字段。
来自 Formik 文档:
handleBlur: (e: any) => void
onBlur
事件处理程序。当您需要跟踪输入是否为 touched
时很有用。这应该传递给 <input onBlur={handleBlur} ... />
handleBlur 是实际更新触摸的方式(或至少是其中一种方式)。如果您的输入未通过连接到 Formik 状态的 onBlur 处理程序,则不会更新触摸状态。
这是一个说明行为的代码和框:https://codesandbox.io/s/magical-gates-4cq5k?file=/src/App.js
如果您对第一个输入进行模糊处理,则 touched 会更新。如果您模糊第二个输入,触摸不会更新。第三个输入使用 useField
,这导致 onBlur
字段自动传递到我的输入。这通常是我喜欢使用 Formik(或几乎任何其他 React 表单库)的方式,因为它减少了将表单字段连接到表单状态所需的样板文件。
import React from "react";
import { Formik, Form, useField } from "formik";
import "./styles.css";
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<Formik
initialValues={{ usingUseField: "", withBlur: "", withoutBlur: "" }}
>
{({ handleChange, handleBlur, values, touched }) => {
return (
<Form>
{JSON.stringify(touched)}
<div>
<label>
With Blur
<input
onBlur={handleBlur("withBlur")}
onChange={handleChange("withBlur")}
value={values.withBlur}
/>
</label>
</div>
<div>
<label>
Without Blur
<input
onChange={handleChange("withoutBlur")}
value={values.withoutBlur}
/>
</label>
</div>
<InputUsingUseField name="usingUseField" label="Using useField" />
</Form>
);
}}
</Formik>
</div>
);
}
function InputUsingUseField({ label, name }) {
const [props] = useField(name);
return (
<div>
<label>
{label}
<input {...props} />
</label>
</div>
);
}