我正在 React Native 项目上使用Formik处理我的登录表单。因此,我将代码分为两个部分:LoginForm.js(使用Formik的地方)和Login.js(渲染登录UI,正在使用LoginForm.js)
当我单击Login.js内的Login按钮时,它应该在LoginForm.js中提交表单(当前正在使用此处的答案进行操作:https://stackoverflow.com/a/53383909)
现在的问题是,我想确保在使用表单内的值登录之前onSubmit已完成。
这是我的组成部分:
Login.js
export default class Login extends React.Component {
submitForm = null
// Method to bind this.submitForm with LoginForm Formik's submitForm
bindSubmitForm = submitForm => {
this.submitForm = submitForm
}
onLoginPressHandler = e => {
if (this.submitForm) {
this.submitForm(e)
// Should login using form values here AFTER submitForm finished
}
}
render() {
return (
<SafeAreaView style={globalStyles.safeAreaContainer}>
<ScrollView
scrollEnabled={false}
contentContainerStyle={styles.scrollViewContent}>
<View style={{ ...globalStyles.container, ...styles.loginView }}>
<LoginForm bindSubmitForm={this.bindSubmitForm} />
<View style={styles.actionButtonsContainer}>
<BlockButton
text="LOGIN"
onPress={this.onLoginPressHandler}
buttonStyle={styles.loginButton}
/>
</View>
</View>
</ScrollView>
</SafeAreaView>
)
}
}
LoginForm.js
export default class LoginForm extends React.Component {
validationSchema = yup.object().shape({
username: yup
.string()
.required()
.label("User Name"),
password: yup
.string()
.required()
.label("Password")
})
render() {
const { bindSubmitForm } = this.props
return (
<View style={{ ...globalStyles.container, ...styles.container }}>
<Formik
initialValues={{ username: "", password: "" }}
validationSchema={this.validationSchema}
onSubmit={(values, { setSubmitting }) => {
console.log("Login Form Submitted")
alert(JSON.stringify(values))
setSubmitting(false)
}}>
{formikProps => {
bindSubmitForm(formikProps.submitForm)
return (
<View>
<FormikTextField
placeholder={"Username"}
formikProps={formikProps}
formikKey={"username"}
/>
<FormikTextField
placeholder={"Password"}
formikProps={formikProps}
formikKey={"password"}
secureTextEntry={true}
/>
</View>
)
}}
</Formik>
</View>
)
}
}
问题:如何等待Formik的onSubmit才能使用表单值登录?