Как добавить входы радиокнопок в React Native с помощью Formik
Переключатели используются при наличии списка из двух или более вариантов, которые взаимоисключают друг друга. У пользователя есть только один выбор из множества вариантов. Эта статья представляет собой полное руководство о том, как реализовать ввод переключателей в формах REACT-NATIVE. Мы будем использовать библиотеку FORMIK.
Шаг 1. Создайте новый проект React Native с помощью expo. Назовите это RadioButtonApp
expo init RadioButtonApp
Шаг 2. Затем установите библиотеку formik в приложение. Читать документацию Formik здесь
npm install formik --save
Шаг 3. Установите Axios
npm install formik --save
Шаг 4. Установите react-native-paper
npm install react-native-paper
Шаг 5. Импортируйте реакцию в файл app.js.
import React from 'react';
Шаг 6. Импортируйте аксиомы в файл app.js.
import axios from 'axios';
Шаг 7. Импортируйте компоненты View, Text и Alert из react-native. в ваш app.js
import { View, Text, Alert} from 'react-native';
Шаг 8. Импортируйте компоненты Button, Title, TextInput и RadioButton из react-native-paper в файл app.js.
import { Button, Title, TextInput, RadioButton } from 'react-native-paper';
Шаг 9. Импортируйте хук useFormik из formik в файл app.js.
import { useFormik } from 'formik';
Это полный список необходимого импорта.
import React from 'react'; import axios from 'axios'; import { View, Text, Alert} from 'react-native'; import { Button, Title, TextInput, RadioButton } from 'react-native-paper'; import { useFormik } from 'formik'
Шаг 10. Создайте постоянную переменную с именем App для хранения функции толстой стрелки.
const App = () => { }; export default App;
Шаг 11. Внутри приложения. Создайте постоянную переменную для хранения возвращаемого значения хука useFormik.
const formik = useFormik();
Шаг 12. Добавьте свойство гендера в свойство initialValues.
const formik = useFormik({ initialValues: { gender: '' }, });
Шаг 13. Для свойства onSubmit отправьте HTTP-запрос с помощью axios, чтобы отправить данные в конечную точку API.
const formik = useFormik({ initialValues: { gender: '' }, onSubmit: values => { axios({ method: 'post', url: 'api end point url', data: { 'gender': values.gender }, }) .then(response => { console.log(response); }) .catch(err => { Alert.alert('An error occurred!', err.message, [{ text: 'Okay' }]); }) } });
В операторе return добавьте группу переключателей
return ( <View> <RadioButton.Group onValueChange={formik.handleChange('gender')} value={formik.values.gender} > <View> <Text>Male</Text> <RadioButton value='M'></RadioButton> </View> <View> <Text>Female</Text> <RadioButton value='F'></RadioButton> </View> </RadioButton.Group> </View> )
Шаг 14. Затем добавьте кнопку отправки под группой переключателей.
return ( <View> <RadioButton.Group onValueChange={formik.handleChange('gender')} value={formik.values.gender} > <View> <Text>Male</Text> <RadioButton value='M'></RadioButton> </View> <View> <Text>Female</Text> <RadioButton value='F'></RadioButton> </View> </RadioButton.Group> <Button mode="contained" title='submit' onPress={formik.handleSubmit} >Enter</Button> </View> )
Окончательный файл app.js должен выглядеть следующим образом.
import React, { useState, useEffect } from 'react'; import axios from 'axios'; import { StyleSheet, View, Text, Image, Alert} from 'react-native'; import { Card, Button, Title, Paragraph, TextInput, RadioButton, Divider } from 'react-native-paper'; import { useFormik } from 'formik'; const App = () => { const formik = useFormik({ initialValues: { gender: '' }, onSubmit: values => { axios({ method: 'post', url: 'api end point url', data: { 'gender': values.gender }, }) .then(response => { console.log(response); }) .catch(err => { Alert.alert('An error occurred!', err.message, [{ text: 'Okay' }]); }) } }); return ( <View> <RadioButton.Group onValueChange={formik.handleChange('gender')} value={formik.values.gender} > <View> <Text>Male</Text> <RadioButton value='M'></RadioButton> </View> <View> <Text>Female</Text> <RadioButton value='F'></RadioButton> </View> </RadioButton.Group> <Button mode="contained" title='submit' onPress={formik.handleSubmit} >Enter</Button> </View> ) }; export default App;
Наконец протестируйте приложение.
И вот оно. Я надеюсь, что вы нашли это полезным. Я вернусь с более интересными статьями. Спасибо за чтение.
Дополнительные материалы на plainenglish.io