React Native

Formik 与 React Native 和 React Native Web 100% 兼容。但是,由于 ReactDOM 和 React Native 在处理表单和文本输入方面存在差异,因此需要注意一些差异。本节将引导你了解它们以及我们认为的最佳实践。

¥Formik is 100% compatible with React Native and React Native Web. However, because of differences between ReactDOM's and React Native's handling of forms and text input, there are some differences to be aware of. This section will walk you through them and what we consider to be best practices.

要旨

¥The gist

在进一步讨论之前,这里有一个关于如何将 Formik 与 React Native 结合使用的超级简单要点,演示了关键区别:

¥Before going any further, here's a super minimal gist of how to use Formik with React Native that demonstrates the key differences:

// Formik x React Native example
import React from 'react';
import { Button, TextInput, View } from 'react-native';
import { Formik } from 'formik';
export const MyReactNativeForm = props => (
<Formik
initialValues={{ email: '' }}
onSubmit={values => console.log(values)}
>
{({ handleChange, handleBlur, handleSubmit, values }) => (
<View>
<TextInput
onChangeText={handleChange('email')}
onBlur={handleBlur('email')}
value={values.email}
/>
<Button onPress={handleSubmit} title="Submit" />
</View>
)}
</Formik>
);

正如你在上面看到的,将 Formik 与 React DOM 和 React Native 结合使用之间的显着区别是:

¥As you can see above, the notable differences between using Formik with React DOM and React Native are:

  1. Formik 的 handleSubmit 被传递给 <Button onPress={...} /> 而不是 HTML <form onSubmit={...} /> 组件(因为 React Native 中没有 <form /> 元素)。

    ¥Formik's handleSubmit is passed to a <Button onPress={...} /> instead of HTML <form onSubmit={...} /> component (since there is no <form /> element in React Native).

  2. <TextInput /> 使用 Formik 的 handleChange(fieldName)handleBlur(fieldName),而不是直接将回调分配给 props,因为我们必须从某个地方获取 fieldName,而使用 React Native,我们无法像在 Web 中那样自动获取它(使用输入名称属性)。你还可以使用 setFieldValue(fieldName, value)setFieldTouched(fieldName, bool) 作为替代。

    ¥<TextInput /> uses Formik's handleChange(fieldName) and handleBlur(fieldName) instead of directly assigning the callbacks to props, because we have to get the fieldName from somewhere and with React Native we can't get it automatically like in web (using input name attribute). You can also use setFieldValue(fieldName, value) and setFieldTouched(fieldName, bool) as an alternative.

Formik 中文网 - 粤ICP备13048890号