如何解决无法使用Formik表单单击按钮
我正在使用Formik进行验证,因此,如果输入为空,则会收到“必需的错误”。
当我单击表单按钮时,应呈现一个列表(UsersFoundList)。该列表在表单之外,并且包含进一步具有按钮的元素。当我第一次单击列表中的那些按钮时,它们不起作用。相反,formik错误开始显示在输入字段上。
仅当我尝试再次提交表单时,才会出现此错误。当我单击其他任何东西时都不会。
const [showFlatList,setShowFlatList] = useState(false);
const handleSubmitForm = (
values: FormValues,helpers: FormikHelpers<FormValues>,) => {
console.log('hello',values.input)
setShowFlatList(true);
helpers.resetForm();
};
return (
<View style={styles.container}>
<View >
<Formik
initialValues={initialValues}
onSubmit={handleSubmitForm}
validationSchema={addRelationValidationSchema}>
{({ handleChange,handleBlur,handleSubmit,values }) => (
<View style={styles.searchFieldContainer}>
<View style={styles.form}>
<FieldInput
handleChange={handleChange}
handleBlur={handleBlur}
value={values.input}
fieldType="input"
icon="user"
placeholderText="E-Mail oder Telefonnummer oder Name"
/>
<ErrorMessage
name="input"
render={(msg) => <ErrorText errorMessage={msg} />}
/>
</View>
<View style={styles.buttonContainer}>
<NewButton buttonText="Suchen" onPress={handleSubmit} />
</View>
</View>
)}
</Formik>
</View>
<View style={styles.listHolder}>
{showFlatList && (
<UsersFoundList/>
)}
</View>
</View>
);
复制的示例: https://snack.expo.io/@nhammad/jealous-beef-jerky
在Android手机中值得注意。不在网络版的codeandbox上。
编辑:刚刚意识到不仅按钮,而且如果我在屏幕上单击任意位置,错误也会再次出现。
解决方法
在表单中,您需要将ref
传递给FieldInput
组件
// get a ref for your field input
const fieldRef = useRef();
const handleSubmitForm = (
values: FormValues,helpers: FormikHelpers<FormValues>,) => {
// on successful submission blur the field
fieldRef.current.blur();
...
};
...
<Form
...
render={() => (
{/* pass the ref to your fieldinput in your form */}
<FieldInput ref={ref} .../>
)}
/>
然后在您的自定义FieldInput
组件中,您需要像这样转发引用:
import React,{ forwardRef } from 'react';
export const FieldInput = forwardRef((props,ref) => {
return (
<Item rounded={rounded} style={[styles.inputItem,style]}>
<Input
ref={ref}
...
/>
/>
)
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。