Je souhaite partager mes 3 approches de gestion des champs de formulaire en cascade.
C'est la 3ème approche et nous allons traiter des champs de formulaire dynamiques.
Remarque, il sera plus facile de comprendre cet article si vous jetez un œil aux 2 approches précédentes.
Première approche, Cascade Form Basic
Deuxième approche, formulaire Cascade amélioré
Commençons,
Il s'agit d'une page de formulaire statique avec 5 champs déroulants.
import React, { useState, useEffect } from "react"; import { ScrollView, View, Text, StyleSheet, TouchableOpacity } from "react-native"; import { Dropdown } from "react-native-element-dropdown"; import { Snackbar } from "react-native-paper"; var snackMsg = ""; export default function App() { const [refreshPage, setRefreshPage] = useState(false); const [visible, setVisible] = useState(false); const onToggleSnackBar = () => setVisible(!visible); const onDismissSnackBar = () => setVisible(false); const resetForm = () => { }; return ( <ScrollView> <p>refreshPage state variable is used to refresh the page in all the situations. </p> <p><img src="https://img.php.cn/upload/article/000/000/000/173363402014343.jpg" alt="Cascading Form React Native Advanced" /></p> <p>Now, These fields are going to be converted as dynamic. </p> <h3> Form Field Object </h3> <p>Previously we had 3 separate objects for 3 different fields, but here all fields data placed under one form field object.<br> </p> <pre class="brush:php;toolbar:false"> . . . const formFields = { country: { fieldId: "country", label: "Country", labelField: "name", valueField: "countryId", parents: [], list: [], selectedItem: {}, selectedValue: null, onValueSelected: () => null, }, state: { fieldId: "state",label: "State",labelField: "name",valueField: "stateId", parents: ["country"],list: [],selectedItem: {},selectedValue: null, onValueSelected: () => null, }, city: { fieldId: "city",label: "City",labelField: "name",valueField: "cityId", parents: ["country", "state"],list: [],selectedItem: {}, selectedValue: null,onValueSelected: () => null, }, village: { fieldId: "village",label: "Village",labelField: "name", valueField: "villageId", parents: ["country", "state", "city"], list: [],selectedItem: {},selectedValue: null, onValueSelected: () => null, }, street: { fieldId: "street",label: "Street",labelField: "name", valueField: "streetId", parents: ["country", "state", "city", "village"], list: [],selectedItem: {},selectedValue: null,onValueSelected: () => null, }, }; . . . export default function App() { . . . }
Toutes ces propriétés d'un champ ont des avantages, seront utiles pour gérer le rendu dynamique.
En itérant les clés de l'objet du champ de formulaire, nous restituons les champs déroulants de manière dynamique, toutes les propriétés requises sont disponibles dans l'objet du champ de formulaire.
export default function App() { . . . return ( <View> <p>handle focus / blur<br> </p> <pre class="brush:php;toolbar:false">var focusField = ""; export default function App() { . . . const changeFocusField = (fld = "") => { focusField = fld; setRefreshPage(!refreshPage); }; . . . }
<ZDropDown . . . isFocus={focusField === ele} onFocus={() => { changeFocusField(ele); }} onBlur={() => changeFocusField("")} onChange={(item) => {}} />
Exemples de données pour les champs pays, état, ville, village et rue.
const listCountry = [ { countryId: "1", name: "india" }, { countryId: "2", name: "uk" }, { countryId: "3", name: "canada" }, { countryId: "4", name: "us" }, ]; const listSate = [ { stateId: "1", countryId: "1", name: "state1_india" }, { stateId: "4", countryId: "2", name: "state1_uk" }, { stateId: "7", countryId: "3", name: "state1_canada" }, { stateId: "10", countryId: "4", name: "state1_us" }, ]; const listCity = [ { cityId: "1", stateId: "1", countryId: "1", name: "city1_state1_country1" }, { cityId: "5", stateId: "2", countryId: "1", name: "city5_state2_country1" }, { cityId: "21",stateId: "7",countryId: "3",name:"city21_state7_country3", }, { cityId: "26",stateId: "9",countryId: "3",name: "city26_state9_country3", }, ]; const listVillage = [ { cityId: "1", villageId: "1", name: "village 1 city 1" }, { cityId: "2", villageId: "5", name: "village 5 city 2" }, { cityId: "3", villageId: "9", name: "village 9 city 3" }, { cityId: "4", villageId: "10", name: "village 10 city 4" }, ]; const listStreet = [ { villageId: "1", streetId: "1", name: "village 1 street 1" }, { villageId: "1", streetId: "109", name: "village 1 street 109" }, { villageId: "2", streetId: "2", name: "village 2 street 2" }, { villageId: "2", streetId: "110", name: "village 2 street 110" }, ]; . . . export default function App() { . . . } . . .
Tout d'abord, du côté des fonctionnalités, nous devons configurer certaines choses importantes. N'oubliez pas que nous avons attribué une méthode vide à la propriété onValueSelected, il est maintenant temps d'attribuer la méthode réelle. Nous devons donc créer 5 méthodes et les attribuer au champ de formulaire respectif.
export default function App() { . . . const allValuesSelected = () => { console.log("All fields value selected"); }; const loadStreet = async () => {}; const loadVillage = async () => {}; const loadCity = async () => {}; const loadState = async () => {}; const loadCountry = async () => {}; const loadPageData = () => { formFields.country.onValueSelected = loadState; formFields.state.onValueSelected = loadCity; formFields.city.onValueSelected = loadVillage; formFields.village.onValueSelected = loadStreet; formFields.street.onValueSelected = allValuesSelected; }; return (. . .); }
Lorsque la valeur Country est sélectionnée, la liste STATE doit être chargée, c'est pourquoi ici la méthode loadState est attribuée à onValueSelected de Country. Et aussi d'autres méthodes assignées.
useEffect(() => { loadPageData(); }, []); return (. . .);
chargez la liste des pays à partir d'exemples de données et appelez-la lors du chargement initial de la page.
const loadCountry = async () => { formFields.country.list = [...listCountry]; setRefreshPage(!refreshPage); }; const loadPageData = () => { formFields.country.onValueSelected = loadState; formFields.state.onValueSelected = loadCity; formFields.city.onValueSelected = loadVillage; formFields.village.onValueSelected = loadStreet; formFields.street.onValueSelected = allValuesSelected; loadCountry(); };
Lorsque la valeur du champ déroulant est sélectionnée, nous devons configurer la valeur du champ de formulaire respectif, supprimer le focus et charger la liste déroulante suivante.
return ( . . . <ZDropDown // . . . onChange={(item) => { fld.selectedItem = item; fld.selectedValue = item[fld.valueField]; focusField = ""; fld.onValueSelected(); }} /> . . . );
onValueSelected est utile, non ?
Lorsque la première liste déroulante (pays) a changé, le reste des champs sera modifié. Il faut donc effacer la liste et les données de tous les autres champs du formulaire. Pour cela, nous écrivons une méthode qui peut effacer les valeurs du champ donné vers le champ de fin.
import React, { useState, useEffect } from "react"; import { ScrollView, View, Text, StyleSheet, TouchableOpacity } from "react-native"; import { Dropdown } from "react-native-element-dropdown"; import { Snackbar } from "react-native-paper"; var snackMsg = ""; export default function App() { const [refreshPage, setRefreshPage] = useState(false); const [visible, setVisible] = useState(false); const onToggleSnackBar = () => setVisible(!visible); const onDismissSnackBar = () => setVisible(false); const resetForm = () => { }; return ( <ScrollView> <p>refreshPage state variable is used to refresh the page in all the situations. </p> <p><img src="https://img.php.cn/upload/article/000/000/000/173363402014343.jpg" alt="Cascading Form React Native Advanced" /></p> <p>Now, These fields are going to be converted as dynamic. </p> <h3> Form Field Object </h3> <p>Previously we had 3 separate objects for 3 different fields, but here all fields data placed under one form field object.<br> </p> <pre class="brush:php;toolbar:false"> . . . const formFields = { country: { fieldId: "country", label: "Country", labelField: "name", valueField: "countryId", parents: [], list: [], selectedItem: {}, selectedValue: null, onValueSelected: () => null, }, state: { fieldId: "state",label: "State",labelField: "name",valueField: "stateId", parents: ["country"],list: [],selectedItem: {},selectedValue: null, onValueSelected: () => null, }, city: { fieldId: "city",label: "City",labelField: "name",valueField: "cityId", parents: ["country", "state"],list: [],selectedItem: {}, selectedValue: null,onValueSelected: () => null, }, village: { fieldId: "village",label: "Village",labelField: "name", valueField: "villageId", parents: ["country", "state", "city"], list: [],selectedItem: {},selectedValue: null, onValueSelected: () => null, }, street: { fieldId: "street",label: "Street",labelField: "name", valueField: "streetId", parents: ["country", "state", "city", "village"], list: [],selectedItem: {},selectedValue: null,onValueSelected: () => null, }, }; . . . export default function App() { . . . }
Cette méthode peut être utilisée pour tous les autres champs déroulants et à des fins de réinitialisation de page.
export default function App() { . . . return ( <View> <p>handle focus / blur<br> </p> <pre class="brush:php;toolbar:false">var focusField = ""; export default function App() { . . . const changeFocusField = (fld = "") => { focusField = fld; setRefreshPage(!refreshPage); }; . . . }
La liste déroulante des États est désormais parfaitement chargée.
Comme avant, nous chargeons les données pour le reste des champs.
<ZDropDown . . . isFocus={focusField === ele} onFocus={() => { changeFocusField(ele); }} onBlur={() => changeFocusField("")} onChange={(item) => {}} />
bien, toutes les listes déroulantes sont remplies avec la liste respective.
Avant d'afficher la liste déroulante, nous devons valider son champ parent. Nous allons donc récupérer les champs parents de l'objet champ de formulaire. Ensuite, répétez-les un par un, validez sa valeur et affichez un avertissement si nécessaire.
const listCountry = [ { countryId: "1", name: "india" }, { countryId: "2", name: "uk" }, { countryId: "3", name: "canada" }, { countryId: "4", name: "us" }, ]; const listSate = [ { stateId: "1", countryId: "1", name: "state1_india" }, { stateId: "4", countryId: "2", name: "state1_uk" }, { stateId: "7", countryId: "3", name: "state1_canada" }, { stateId: "10", countryId: "4", name: "state1_us" }, ]; const listCity = [ { cityId: "1", stateId: "1", countryId: "1", name: "city1_state1_country1" }, { cityId: "5", stateId: "2", countryId: "1", name: "city5_state2_country1" }, { cityId: "21",stateId: "7",countryId: "3",name:"city21_state7_country3", }, { cityId: "26",stateId: "9",countryId: "3",name: "city26_state9_country3", }, ]; const listVillage = [ { cityId: "1", villageId: "1", name: "village 1 city 1" }, { cityId: "2", villageId: "5", name: "village 5 city 2" }, { cityId: "3", villageId: "9", name: "village 9 city 3" }, { cityId: "4", villageId: "10", name: "village 10 city 4" }, ]; const listStreet = [ { villageId: "1", streetId: "1", name: "village 1 street 1" }, { villageId: "1", streetId: "109", name: "village 1 street 109" }, { villageId: "2", streetId: "2", name: "village 2 street 2" }, { villageId: "2", streetId: "110", name: "village 2 street 110" }, ]; . . . export default function App() { . . . } . . .
Enfin, nous proposons la possibilité de réinitialiser les champs du formulaire.
export default function App() { . . . const allValuesSelected = () => { console.log("All fields value selected"); }; const loadStreet = async () => {}; const loadVillage = async () => {}; const loadCity = async () => {}; const loadState = async () => {}; const loadCountry = async () => {}; const loadPageData = () => { formFields.country.onValueSelected = loadState; formFields.state.onValueSelected = loadCity; formFields.city.onValueSelected = loadVillage; formFields.village.onValueSelected = loadStreet; formFields.street.onValueSelected = allValuesSelected; }; return (. . .); }
Tout est fait. Nous avons maintenant vu comment gérer les champs de formulaire dynamiques, rendre les champs, charger les données et les valider.
Ce sont mes 3 approches pour gérer les champs de formulaire en cascade.
J'espère que cet article/série contient des éléments utiles que vous aimez. Merci.
Code complet ici
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!