我想分享我處理級聯表單欄位的 3 種方法。
- 第一個是通用方法,使用狀態變數。
- 第二種是使用普通變數和一個布林狀態變數來觸發狀態效果(刷新頁面)。
- 第三種是帶有普通變數的動態表單欄位。
第一種方法,使用狀態變數
在這篇文章中,我們看到了第二種方法,使用普通變數來處理基於國家、州、城市資料的級聯表單欄位。
套餐
react-native-element-dropdown react-native-paper
我們正在使用react-native-element-dropdown作為下拉欄位
基頁
import React, { useState, useEffect } from "react"; import { View, Text, StyleSheet, TouchableOpacity } from "react-native"; import { Dropdown } from "react-native-element-dropdown"; export default function App() { return ( <view> <p>ZDropDown is a custom component. </p> <h3> Sample data </h3> <pre class="brush:php;toolbar:false">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: "6", stateId: "2", countryId: "1", name: "city6_state2_country1", }, { cityId: "7", stateId: "3", countryId: "1", name: "city7_state3_country1", }, { cityId: "23", stateId: "8", countryId: "3", name: "city23_state8_country3", }, { cityId: "30", stateId: "10", countryId: "4", name: "city30_state10_country4", }, { cityId: "35", stateId: "12", countryId: "4", name: "city35_state12_country4", }, { cityId: "36", stateId: "12", countryId: "4", name: "city36_state12_country4", }, ];
表單變數
第一種方法中我們使用了4 個狀態變量,但這裡我們使用4 個普通變量(3 個用於下拉,1 個用於焦點字段)和一個用於切換和觸發狀態效果(刷新頁面)的狀態變數。
var country = { list: [], selectedCountry: {}, selectedValue: null, }; var state = { list: [], selectedState: {}, selectedValue: null, }; var city = { list: [], selectedCity: {}, selectedValue: null, }; var focusField = ''; export default function App() { const [refreshPage, setRefreshPage] = useState(false); return ( <view> <p>Focus and Blur events get triggered more than onChange event so it is better to maintain a separate variable to represent the focus field and avoid data mess up situations. </p> <h3> Load Country </h3> <p>Load country dropdown from the sample data. (you can use api call)<br> </p> <pre class="brush:php;toolbar:false">export default function App() { . . . const loadCountry = () => { // load data from api call country.list = [...listCountry]; // switching value will refresh the ui setRefreshPage(!refreshPage); }; useEffect(() => { loadCountry(); }, []); return ( . . . )
對焦/模糊
我們使用一個函數來設定焦點欄位並透過切換狀態變數(refreshPage)來刷新頁面
const changeFocusField = (fld = '') => { focusField = fld; setRefreshPage(!refreshPage); };
<text>Country</text> <zdropdown . isfocus="{focusField" onfocus="{()"> changeFocusField('country')} onBlur={() => changeFocusField('')} onChange={null} /> <text>State</text> <zdropdown . isfocus="{focusField" onfocus="{()"> changeFocusField('state')} onBlur={() => changeFocusField('')} onChange={null} /> <text>City</text> <zdropdown . isfocus="{focusField" onfocus="{()"> changeFocusField('city')} onBlur={() => changeFocusField('')} onChange={null} /> </zdropdown></zdropdown></zdropdown>
我們現在已經完成一半了。
載入狀態狀態
在所選的國家/地區,我們需要根據所選國家/地區加載相應的州 STATES。
更新國家/地區字段,關注國家/地區並根據國家/地區加載州。
<text>Country</text> <zdropdown . onchange="{(item)"> { country.selectedCountry = item; country.selectedValue = item.countryId; focusField = ''; loadState(); }} /> </zdropdown>
您看到第一種方法的差別了嗎?之前更新了 3 個狀態變量,但這裡只更新了 1 個狀態變數。
當國家/地區發生變化時,州和城市都會發生變化。因此,在設定新值之前,我們需要清除現有資料。
const loadState = async () => { state = { list: [], selectedState: {}, selectedValue: null }; city = { list: [], selectedCity: {}, selectedValue: null }; const arr = listSate.filter( (ele) => ele.countryId === country.selectedValue ); if (arr.length) { state.list = arr; } refreshPage(!refreshPage); };
負載城市
並根據國家和州載入城市欄位。
<text>State</text> <zdropdown . onchange="{(item)"> { state.selectedValue = item.stateId; state.selectedState = item; changeFocusField(''); loadCity(); }} /> </zdropdown>
const loadCity = async () => { city = { list: [], selectedCity: {}, selectedValue: null }; const arr = listCity.filter((ele) => ele.stateId === state.selectedValue); if (arr.length) city.list = arr; setRefreshPage(!refreshPage); };
一切就緒,表單欄位現在可以正常運作了。
還有2個附加功能,一是重置頁面,二是顯示警告。
重置頁面
表單變數和焦點變數應該被清除。
. . . const resetForm = () => { country = {list: [...listCountry],selectedCountry: {}, selectedValue: null}; state = { list: [], selectedState: {}, selectedValue: null }; city = { list: [], selectedCity: {}, selectedValue: null }; focusField = ''; setRefreshPage(!refreshPage); }; . . . <touchableopacity onpress="{()"> resetForm()}> <h3> Warning </h3> <p>We have to show a warning msg if the parent field value is null. For that we are using SnackBar component from paper.<br> </p> <pre class="brush:php;toolbar:false">import { Snackbar } from "react-native-paper"; . . . var snackMsg = ''; export default function App() { . . . const [visible, setVisible] = useState(false); const onToggleSnackBar = () => setVisible(!visible); const onDismissSnackBar = () => setVisible(false); . . . return ( <view> <p>We moved snackMsg to ordinary variable from state variable.</p> <p>Since State and City fields have parent field, they have to be validated.<br> </p> <pre class="brush:php;toolbar:false"> <text>State</text> <zdropdown onfocus="{()"> { focusField('state'); if (!country.selectedValue) { snackMsg = 'Select country'; onToggleSnackBar(); changeFocusField('country'); } }} . . . /> <text>City</text> <zdropdown onfocus="{()"> { focusField('city'); if (!country.selectedValue) { snackMsg = 'Select country'; onToggleSnackBar(); changeFocusField('country'); } else if (!state.selectedValue) { snackMsg = 'Select state'; onToggleSnackBar(); changeFocusField('state'); } }} . . . /> </zdropdown></zdropdown>
完成。
謝謝。
完整程式碼參考這裡
以上是級聯形式 React Native 改進的詳細內容。更多資訊請關注PHP中文網其他相關文章!

我使用您的日常技術工具構建了功能性的多租戶SaaS應用程序(一個Edtech應用程序),您可以做同樣的事情。 首先,什麼是多租戶SaaS應用程序? 多租戶SaaS應用程序可讓您從唱歌中為多個客戶提供服務

本文展示了與許可證確保的後端的前端集成,並使用Next.js構建功能性Edtech SaaS應用程序。 前端獲取用戶權限以控制UI的可見性並確保API要求遵守角色庫

JavaScript是現代Web開發的核心語言,因其多樣性和靈活性而廣泛應用。 1)前端開發:通過DOM操作和現代框架(如React、Vue.js、Angular)構建動態網頁和單頁面應用。 2)服務器端開發:Node.js利用非阻塞I/O模型處理高並發和實時應用。 3)移動和桌面應用開發:通過ReactNative和Electron實現跨平台開發,提高開發效率。

JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。

Python更适合数据科学和机器学习,JavaScript更适合前端和全栈开发。1.Python以简洁语法和丰富库生态著称,适用于数据分析和Web开发。2.JavaScript是前端开发核心,Node.js支持服务器端编程,适用于全栈开发。

JavaScript不需要安裝,因為它已內置於現代瀏覽器中。你只需文本編輯器和瀏覽器即可開始使用。 1)在瀏覽器環境中,通過標籤嵌入HTML文件中運行。 2)在Node.js環境中,下載並安裝Node.js後,通過命令行運行JavaScript文件。

如何在Quartz中提前發送任務通知在使用Quartz定時器進行任務調度時,任務的執行時間是由cron表達式設定的。現�...


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

禪工作室 13.0.1
強大的PHP整合開發環境

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)