你应该做的是有一个模态或类似的东西来显示错误。
当使用Formik 时,您渲染的组件(您可以使用component、render 和children)将收到带有错误的道具,如您在docs 的示例中所见。
<Formik> {// getting the errors here }
{({ handleSubmit, handleChange, handleBlur, values, errors }) => (
<form onSubmit={handleSubmit}>
<input
type="text"
onChange={handleChange}
onBlur={handleBlur}
value={values.name}
name="name"
/>
{errors.name &&
<div>
{errors.name}
</div>}
<button type="submit">Submit</button>
</form>
)}
</Formik>
errors 将是一个对象,因此您检查errors 的keys(或者您也可以使用values)并决定您是否会呈现错误模式。
<Formik
validationSchema={yourValidationSchema}
onSubmit={whatYouWantTodoWhenEverythingIsGood}
initialValues={{ email: '' }}
>
{({ errors, values, handleChange, handleBlur}) => (
<View>
<TextInput
onChangeText={handleChange('email')}
onBlur={handleBlur('email')}
value={values.email}
/>
<Button onPress={props.handleSubmit} title="Submit" />
{// checking if you have errors}
{
Object.keys(errors).length > 0 &&
<Modal errors={errors}/>
}
</View>
)}
</Formik>
根据您的模态来自哪里,您可以使用<Modal isActive={Object.keys(errors).length > 0} errors={errors}/> 或其他类似的东西。
例如使用react-native modal
<Modal
visible={Object.keys(errors).length > 0}
>
<View>
{// show the errors the way you want}
</View>
</Modal>
您应该使用Object.keys(errors).length > 0 来决定是否应该使用errors 显示模态框。