簡體   English   中英

如何在 React.js 的單個組件中根據選定的國家/地區下拉列表兩次填充 State 下拉列表數據?

[英]How to populate State dropdown data as per selected Country dropdown two times in a single component in React.js?

我想根據所選國家/地區填充 state 數據。 這工作正常。

但是我有兩個在一個頁面中多次使用這個條件。 我怎樣才能做到這一點?

附上問題截圖:- 在此處輸入圖像描述

沙盒 Url:- https://codesandbox.io/s/country-state-sibling-issue-rdphoc?file=/src/App.js

我的代碼:-

 import React, { useState, useEffect } from "react"; import "./styles.css"; import { TextField, MenuItem } from "@mui/material"; export default function App() { const body = [ { state_ID: 1, state: "Delhi", country_ID: 1, country_name: "India" }, { state_ID: 2, state: "Mumbai", country_ID: 1, country_name: "India" }, { state_ID: 3, state: "Calgary", country_ID: 2, country_name: "Canada" }, { state_ID: 4, state: "Toronto", country_ID: 2, country_name: "Canada" } ]; const [country, setCountry] = useState([]); const [state, setState] = useState([]); const [selectedCountry, setSelectedCountry] = useState(""); useEffect(() => { const uniqValues = [...new Map(body.map((item) => [item["country_name"], item])).values() ]; setCountry(uniqValues); setState(body); }, []); useEffect(() => { const newStates = body.filter( ({ country_name }) => country_name === selectedCountry ); console.log(selectedCountry, newStates); setState(newStates); }, [selectedCountry]); useEffect(() => {}, [body, country]); return ( <> <TextField className="ruleContainer" select name="Country" label="Country" variant="outlined" size="small" onChange={(event) => setSelectedCountry(event.target.value)} > {country? country.map((opt) => ( <MenuItem key={opt.country_name} value={opt.country_name} onChange={(value) => setSelectedCountry(value)} > {opt.country_name} </MenuItem> )): ""} </TextField> <TextField className="ruleContainer" select name="state" label="State" variant="outlined" size="small" value="" > {state? state.map((opt) => ( <MenuItem key={opt.state} value={opt.state}> {opt.state} </MenuItem> )): ""} </TextField> <hr /> <TextField className="ruleContainer" select name="Country" label="Country" variant="outlined" size="small" onChange={(event) => setSelectedCountry(event.target.value)} > {country? country.map((opt) => ( <MenuItem key={opt.country_name} value={opt.country_name} onChange={(value) => setSelectedCountry(value)} > {opt.country_name} </MenuItem> )): ""} </TextField> <TextField className="ruleContainer" select name="state" label="State" variant="outlined" size="small" value="" > {state? state.map((opt) => ( <MenuItem key={opt.state} value={opt.state}> {opt.state} </MenuItem> )): ""} </TextField> <hr /> </> ); }

感謝您的努力!

實現多個相同的 forms with country 和 state dependent。 您需要使用這些表單字段創建自定義組件並在其中維護 state。 所以不會影響主組件state。

在此處輸入圖像描述

您可以在https://codesandbox.io/s/country-state-sibling-issue-forked-9wcmi9?file=/src/App.js找到工作示例

CountryStateFormItems 組件

import { useState, useEffect } from "react";
import { TextField, MenuItem, Box } from "@mui/material";

const body = [
  {
    state_ID: 1,
    state: "Delhi",
    country_ID: 1,
    country_name: "India"
  },
  {
    state_ID: 2,
    state: "Mumbai",
    country_ID: 1,
    country_name: "India"
  },
  {
    state_ID: 3,
    state: "Calgary",
    country_ID: 2,
    country_name: "Canada"
  },
  {
    state_ID: 4,
    state: "Toronto",
    country_ID: 2,
    country_name: "Canada"
  }
];

export default function CountryStateFormItems(props) {
  const [country, setCountry] = useState([]);
  const [state, setState] = useState([]);
  const [selectedCountry, setSelectedCountry] = useState(props.form.country);
  const [selectedState, setSelectedState] = useState(props.form.state);

  useEffect(() => {
    const uniqValues = [
      ...new Map(body.map((item) => [item["country_name"], item])).values()
    ];
    setCountry(uniqValues);
  }, []);

  useEffect(() => {
    const newStates = body.filter(
      ({ country_name }) => country_name === selectedCountry
    );
    setState(newStates);
  }, [selectedCountry]);

  useEffect(() => {
    props.updateForm(props.index, selectedCountry, selectedState);
  }, [selectedState]);

  return (
    <>
      <Box display="flex">
        <TextField
          style={{ flex: 1 }}
          className="ruleContainer"
          select
          name="Country"
          label="Country"
          variant="outlined"
          size="small"
          value={selectedCountry}
          onChange={(event) => setSelectedCountry(event.target.value)}
        >
          {country
            ? country.map((opt) => (
                <MenuItem
                  key={opt.country_name}
                  value={opt.country_name}
                  onChange={(value) => setSelectedCountry(value)}
                >
                  {opt.country_name}
                </MenuItem>
              ))
            : ""}
        </TextField>
        &nbsp;
        <TextField
          style={{ flex: 1 }}
          className="ruleContainer"
          select
          name="state"
          label="State"
          variant="outlined"
          size="small"
          value={selectedState}
          onChange={(event) => setSelectedState(event.target.value)}
        >
          {state
            ? state.map((opt) => (
                <MenuItem
                  key={opt.state}
                  value={opt.state}
                  onChange={(value) => setSelectedState(value)}
                >
                  {opt.state}
                </MenuItem>
              ))
            : ""}
        </TextField>
      </Box>
      <hr />
    </>
  );
}

應用組件

import React, { useState, useCallback } from "react";
import "./styles.css";
import { Button } from "@mui/material";
import CountryStateFormItems from "./CountryStateFormItems";

export default function App() {
  const [forms, setForms] = useState([]);

  const addForm = () => {
    const existingForms = [...forms];
    existingForms.push({
      country: "",
      state: ""
    });
    setForms(existingForms);
  };

  const updateForm = useCallback(
    (index, country, state) => {
      const existingForms = [...forms];
      existingForms[index].country = country;
      existingForms[index].state = state;
      setForms(existingForms);
    },
    [forms, setForms]
  );

  const printForm = () => {
    console.log(forms);
  };

  return (
    <>
      <Button variant="contained" onClick={addForm}>
        Add
      </Button>
      &nbsp;
      <Button variant="contained" onClick={printForm}>
        Print
      </Button>
      <hr />
      {forms
        ? forms.map((form, index) => (
            <CountryStateFormItems
              key={index}
              index={index}
              form={form}
              updateForm={updateForm}
            />
          ))
        : ""}
    </>
  );
}

您可以使用兩個 state 變量來存儲這兩個國家。 例如:

const [selectedCountry1, setSelectedCountry2] = useState("");
const [selectedCountry2, setSelectedCountry2] = useState("");

同樣,您也可以使用 2 個變量來存儲國家/地區的state值。


或者,您也可以將其存儲在帶有多個密鑰的單個 state object 中,例如:

const [selectedCountriesObject, setSelectedCountriesObject] = useState({ country1: "", country2: ""});

您需要管理 state 中的對象數組。這里有一個很好的資源來解釋如何做到這一點: 管理 State 數組 我希望它有所幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM