首頁 >web前端 >js教程 >級聯形式 React Native 改進

級聯形式 React Native 改進

Barbara Streisand
Barbara Streisand原創
2024-12-06 01:02:11481瀏覽

我想分享我處理級聯表單欄位的 3 種方法。

  1. 第一個是通用方法,使用狀態變數。
  2. 第二種是使用普通變數和一個布林狀態變數來觸發狀態效果(刷新頁面)。
  3. 第三種是帶有普通變數的動態表單欄位。

第一種方法,使用狀態變數

在這篇文章中,我們看到了第二種方法,使用普通變數來處理基於國家、州、城市資料的級聯表單欄位。

套餐

react-native-element-dropdown
react-native-paper

我們正在使用react-native-element-dropdown作為下拉欄位

基頁

Cascading form React Native Improved

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 === 'country'}
          onFocus={() => changeFocusField('country')}
          onBlur={() => changeFocusField('')}
          onChange={null}
        />
        <Text>State</Text>
        <ZDropDown
        . . .
          isFocus={focusField === 'state'}
          onFocus={() => changeFocusField('state')}
          onBlur={() => changeFocusField('')}
          onChange={null}
        />
        <Text>City</Text>
        <ZDropDown        
        . . .
          isFocus={focusField === 'city'}
          onFocus={() => changeFocusField('city')}
          onBlur={() => changeFocusField('')}
          onChange={null}       
        />

Cascading form React Native Improved

我們現在已經完成一半了。

載入狀態狀態

在所選的國家/地區,我們需要根據所選國家/地區加載相應的 STATES。

更新國家/地區字段,關注國家/地區並根據國家/地區加載州。

  <Text>Country</Text>
  <ZDropDown
    . . .
    onChange={(item) => {
      country.selectedCountry = item;
      country.selectedValue = item.countryId;
      focusField = '';
      loadState();
    }}
  />

您看到第一種方法的差別了嗎?之前更新了 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);
 };

Cascading form React Native Improved

負載城市

並根據國家和州載入城市欄位。

    <Text>State</Text>
    <ZDropDown
      . . .
      onChange={(item) => {
        state.selectedValue = item.stateId;
        state.selectedState = item;
        changeFocusField('');
        loadCity();
      }}
     />
  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);
  };

Cascading form React Native Improved

一切就緒,表單欄位現在可以正常運作了。

Cascading form React Native Improved

還有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');
            }
          }}
          . . .
        />

Cascading form React Native Improved

完成。

謝謝。

完整程式碼參考這裡

以上是級聯形式 React Native 改進的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn