我有一个简单的组件,如下所示,它基本上尝试使用 useFormikContext 挂钩从 formik FormContext 中获取一些数据。
然而,当尝试为此组件编写单元测试时,它希望我模拟钩子,这很好,但是,使用打字稿模拟钩子意味着返回超过 20 个属性,其中大多数是各种方法和函数。
有没有人找到更好的方法来做到这一点?即使我让它工作,似乎也有点烦人,因为我只需要钩子中的 1 个字段。
成分
const AphControlInput: React.FC<IAphControlInput> = ({ name, value, label, type, small, disabled, vertical = true, className = '', ...attributeOptions }) => {
const form = useFormikContext();
return (
<>
<div className={
`aph-control-input ${className}` +
`${small ? ' aph-control-input--small' : ''}` +
`${vertical ? ' aph-control-input--block' : ''}` +
`${form.getFieldMeta(name).error ? ' aph-control-input--invalid' : ''}`
}
>
<Field
className='aph-control-input__input'
name={name}
id={value ? value?.toString() : name}
type={type}
value={value ? value …Run Code Online (Sandbox Code Playgroud) 问题
我有一个 formik 表单,需要有 2 个不同的验证模式,具体取决于用户使用哪个按钮提交。我看到有些人说使用状态来决定哪个,但我想避免使用状态,因为在这种情况下感觉不对。
我已经查看了Yup 的文档,似乎您可以直接使用模式并传递值进行验证。这似乎是有效的,正如我在示例中所示的那样,但是它返回的验证错误是无用的,我需要将它们转换为能够使用 Formik setErrors 帮助器。
是的,根据文档进行验证
let validationErrors = null;
try {
// Validate the form data using a custom Schema
await createDraftContractorFormValidationSchema.validate(values, { abortEarly: false, strict: false });
}
catch (errors: any) {
console.log(errors);
// What I essentially need here is a way to transform these errors
// into an object with the keys being the field that has errors and the message
if (errors) {
formikRef.current.setErrors(errors);
}
}
Run Code Online (Sandbox Code Playgroud)
记录什么
ValidationError: …Run Code Online (Sandbox Code Playgroud)