我在自己的React中使用formik,如:在构造函数this.myRef = React.createRef();
中
创建我的表单组件如下所示
<AppForm
innerRef={this.myRef}
initialValues={{ currentPassword: '', newPassword: '', confirmPassword: '' }}
validationSchema={validationSchema}
onSubmit={() => ''}
>
<AppFormField
heading='Current Password'
name='currentPassword'
autoCapitalize='none'
secureTextEntry={!showCurrentPassword}
icon={showCurrentPassword ? 'eye' : 'eye-off'}
onIconClick={() => this.setState({ showCurrentPassword: !showCurrentPassword })}
/>
</AppForm>
其中AppForm是我的自定义表单组件,AppFormField是一个自定义组件。
(我使用的是ref bcz,我在表单组件之外使用Save按钮提交表单)
调用句柄提交如下所示的onBtnPress={() => this.handleSubmit()}
最后,我要设置错误的handleSubmit函数。
handleSubmit = async () => {
this.myRef.current?.submitForm();
this.myRef.current.setErrors({currentPassword: 'Hello'});
this.myRef.current.setFieldError('currentPassword', 'Hello'); // I've tried both ways
console.log('CurrentRef ', this.myRef.current);
}
我尝试过setErrors和setFieldError,并期望formik将错误"Hello“设置为'currentPassword‘字段,但我无法这样做。如果有错误,请告诉我,并告诉我正确的方法。
谢谢!
发布于 2022-06-16 19:23:51
实际上,问题在于我调用这个方法的方式。setFieldError
和setErrors
都是异步,我在没有等待的情况下调用了它们。
发布于 2021-12-28 16:52:22
A.You需要在Formik组件中添加errors
B.你使用setFieldError
调用者setFieldError("currentPassword", "Hello")
(信息)
https://stackoverflow.com/questions/70509983
复制相似问题