我正在使用 native base 的输入字段,并尝试使用 Formik 和 Yup 对其进行验证。但是,到目前为止,还没有进行任何验证。即使我输入字母,它也不会显示任何错误。
此代码有效(没有 Formik):
type EmailRegistrationProps = {};
interface FormValues {
friendEmail: string;
}
type AddFriendEmailPageProps = {
toggleShowPage: () => void;
showAddFriendEmailPage: boolean;
};
export const AddFriendEmailPage: React.FunctionComponent<AddFriendEmailPageProps> = ({
toggleShowPage,
showAddFriendEmailPage,
}) => {
const [friendEmail, setFriendEmail] = useState('');
const [errorMessage, setErrorMessage] = useState('');
const validationSchema = emailValidationSchema;
const showAlert = () => {
Alert.alert('Friend Added');
}
useEffect(() => {
if (showAddFriendEmailPage) return;
setFriendEmail('');
}, [showAddFriendEmailPage]);
const _onLoadUserError = React.useCallback((error: ApolloError) => {
setErrorMessage(error.message);
Alert.alert('Unable to Add Friend');
}, []);
const [
createUserRelationMutation,
{
data: addingFriendData,
loading: addingFriendLoading,
error: addingFriendError,
called: isMutationCalled,
},
] = useCreateUserRelationMutation({
onCompleted : ( data: any) => {
showAlert();
}
});
const addFriend = React.useCallback(
(id: Number) => {
console.log('Whats the Id', id);
createUserRelationMutation({
variables: {
input: { relatedUserId: id, type: RelationType.Friend, userId: 7 },
},
});
},
[createUserRelationMutation],
);
const getFriendId = React.useCallback(
(data: any) => {
console.log('Email', friendEmail);
if (data) {
if (data.users.nodes.length == 0) {
setErrorMessage('User Not Found');
} else {
addFriend(Number(data.users.nodes[0].id));
}
}
},
[friendEmail, addFriend],
);
const [loadUsers] = useUsersLazyQuery({
onCompleted: getFriendId,
onError: _onLoadUserError,
});
const handleSubmit = React.useCallback(() => {
loadUsers({
variables: {
where: { email: friendEmail },
},
});
setFriendEmail('');
}, [loadUsers, friendEmail]);
}
return (
<Modal
visible={showAddFriendEmailPage}
animationType="slide"
transparent={true}>
<SafeAreaView>
<View style={scaledAddFriendEmailStyles.container}>
<View style={scaledAddFriendEmailStyles.searchTopContainer}>
<View style={scaledAddFriendEmailStyles.searchTopTextContainer}>
<Text
style={scaledAddFriendEmailStyles.searchCancelDoneText}
onPress={toggleShowPage}>
Cancel
</Text>
<Text style={scaledAddFriendEmailStyles.searchTopMiddleText}>
Add Friend by Email
</Text>
<Text style={scaledAddFriendEmailStyles.searchCancelDoneText}>
Done
</Text>
</View>
<View style={scaledAddFriendEmailStyles.searchFieldContainer}>
<Item style={scaledAddFriendEmailStyles.searchField}>
<Input
placeholder="Email"
style={scaledAddFriendEmailStyles.searchText}
onChangeText={(text) => setFriendEmail(text)}
value={friendEmail}
autoCapitalize="none"
/>
</Item>
<View style={scaledAddFriendEmailStyles.buttonContainer}>
<Button
rounded
style={scaledAddFriendEmailStyles.button}
onPress={() => handleSubmit()}
>
<Text style={scaledAddFriendEmailStyles.text}>
Add Friend{' '}
</Text>
</Button>
</View>
{/* </View>
)}
</Formik> */}
</View>
</View>
</View>
</SafeAreaView>
</Modal>
);
};
现在我正在尝试添加 Formik:
编辑:
export const AddFriendEmailPage: React.FunctionComponent<AddFriendEmailPageProps> = ({
toggleShowPage,
showAddFriendEmailPage,
}) => {
const initialValues: FormValues = {
friendEmail: '',
};
//const [friendEmail, setFriendEmail] = useState('');
const [errorMessage, setErrorMessage] = useState('');
const validationSchema = emailValidationSchema;
const showAlert = () => {
Alert.alert('Friend Added');
}
useEffect(() => {
if (showAddFriendEmailPage) return;
initialValues.friendEmail = '';
}, [showAddFriendEmailPage]);
const _onLoadUserError = React.useCallback((error: ApolloError) => {
setErrorMessage(error.message);
Alert.alert('Unable to Add Friend');
}, []);
const [
createUserRelationMutation,
{
data: addingFriendData,
loading: addingFriendLoading,
error: addingFriendError,
called: isMutationCalled,
},
] = useCreateUserRelationMutation({
onCompleted : ( data: any) => {
showAlert();
}
});
const addFriend = React.useCallback(
(id: Number) => {
console.log('Whats the Id', id);
createUserRelationMutation({
variables: {
input: { relatedUserId: id, type: RelationType.Friend, userId: 7 },
},
});
},
[createUserRelationMutation],
);
const getFriendId = React.useCallback(
(data: any) => {
console.log('Email', friendEmail);
if (data) {
if (data.users.nodes.length == 0) {
console.log('No user');
setErrorMessage('User Not Found');
Alert.alert('User Not Found');
} else {
console.log('ID', data.users.nodes[0].id);
addFriend(Number(data.users.nodes[0].id));
}
}
},
[friendEmail, addFriend],
);
const [loadUsers] = useUsersLazyQuery({
onCompleted: getFriendId,
onError: _onLoadUserError,
});
const handleSubmit = React.useCallback((
values: FormValues,
helpers: FormikHelpers<FormValues>,
) => {
console.log('Submitted');
loadUsers({
variables: {
where: { email: values.friendEmail },
},
});
//setFriendEmail('');
values.friendEmail = '';
}, [loadUsers, initialValues.friendEmail]);
}
return (
<Modal
visible={showAddFriendEmailPage}
animationType="slide"
transparent={true}>
<SafeAreaView>
<View style={scaledAddFriendEmailStyles.container}>
<View style={scaledAddFriendEmailStyles.searchTopContainer}>
<View style={scaledAddFriendEmailStyles.searchTopTextContainer}>
<Text
style={scaledAddFriendEmailStyles.searchCancelDoneText}
onPress={toggleShowPage}>
Cancel
</Text>
<Text >
Add Friend by Email
</Text>
<Text>
Done
</Text>
</View>
<View style={scaledAddFriendEmailStyles.searchFieldContainer}>
<Formik
initialValues={initialValues}
onSubmit={handleSubmit}
validationSchema={validationSchema}>
{({
handleChange,
handleBlur,
handleSubmit,
isSubmitting,
values,
}) => (
<Field
component={Input}
placeholder="Email"
onChangeText={handleChange('friendEmail')}
onBlur={handleBlur('friendEmail')}
value={values.friendEmail}
autoCapitalize="none"
/>
)}
</Formik>
<View >
<Button
onPress={() => handleSubmit()}
>
<Text >
Add Friend{' '}
</Text>
</Button>
</View>
</View>
</View>
</View>
</SafeAreaView>
</Modal>
);
};
目前,这对我不起作用。我想继续使用我通过 onPress 按钮使用的旧 handleSubmit。但是现在我不知道如何将值、助手传递到这个 handleSubmit 中:
onPress={() => handleSubmit()}
我得到
Expected 2 arguments, but got 0.
但是,如果我尝试传递
values, helpers
,则找不到这些名称。同样,我正在使用
[friendEmail, addFriend],
在
getFriendId
的末尾。如果我只使用 setState 而没有 formik 验证等,这可以正常工作。但是现在找不到 friendEmail
。我只是无法以这样的方式正确合并 Formik,我也可以像使用 useState
一样重置值。 最佳答案
Formik 要求您使用 <Field />
组件进行验证。
您可以通过 component
prop 设置自定义组件。
在您的情况下,例如:
<Field
component={Input}
name="phoneNumber"
placeholder="Phone Number"
onChangeText={handleChange}
onBlur={handleBlur}
type='tel'
value={values.phoneNumber}
/>
更新
啊,糟糕,我更新了
onChangeText
和 onBlur
以反射(reflect)更改。在当前的实现中,您实际上是在加载时而不是在偶数发生时运行“处理”事件。如果您 name
输入它应该自动传递该信息。此外,您应该为输入设置类型。我已经为所有这些更新更新了上述示例。关于javascript - 原生基础输入的 Formik 验证,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61499741/