簡體   English   中英

如何動態加載多選? [反應選擇]

[英]How can I load multi select dynamically? [react-select]

如何動態加載多選? 我使用 react-select 來實現 MultiSelect。

我的努力

在 componentDidMount() 中,我獲取了一個數組,我想在我的多選中顯示/加載它; 然后將響應存儲在狀態中。

現在,我試圖從那個狀態中獲取價值,但我沒有得到那個價值。

我的代碼

state= {Category: []}

// that category contain this values
//0: {categoryid: "1", categoryname: "Select Category"}
//1: {categoryid: "2", categoryname: "Abc"}


componentDidMount() {
    fetch("http://myURL//file.php", {
      method: "POST",

      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify({})
    })
      .then(response => response.json())
      .then(responseJson => {
        this.setState({ Category: responseJson });
        //  If server response message same as Data Matched

        console.log(this.state.Category);
        window.parent.location = window.parent.location.href;
      })
      .catch(error => {
        console.error(error);
      });
  }

//this code is not working, display nothing

  <Select
    closeMenuOnSelect={false}
    components={animatedComponents}
    isMulti
  >
    {this.state.Category.map((e, key) => {
      return (
        <option key={key} value={e.categoryid}>
          {e.categoryname}
        </option>
      );
    })}
  </Select>

請幫我解決這個問題

react-select 有選項道具。

<Select
    closeMenuOnSelect={false}
    components={animatedComponents}
    options={this.state.Category.map(e => ({ label: e.categoryname, value: e.categoryid}))}
    isMulti
    onChange={newValue => this.setState({ selected: newValue })}
  />

如何根據另一個選擇組件選擇此多選的值?

您可以根據選定的值存儲選擇狀態和過濾選項的選定值。

我添加了帶有 2 個依賴選擇的快速樣本 - 醫院(可以有少數醫生)和醫生(可以在少數醫院工作)。

當您選擇某些醫生 - 醫院選擇會更新,反之亦然。

預覽此代碼

    import React, { useState } from "react";
    import { render } from "react-dom";
    import Select from "react-select";
    
    const data = {
      doctors: [
        {
          id: 1,
          name: "Andrew",
          hospitals: [{ id: 1, title: "Test Hospital" }, { id: 2, title: "Test2" }]
        },
        {
          id: 2,
          name: "Another",
          hospitals: [{ id: 1, title: "Test Hospital" }, { id: 3, title: "Test3" }]
        }
      ],
      hospitals: [
        { id: 1, title: "Test Hospital" },
        { id: 2, title: "Test2" },
        { id: 3, title: "Test3" }
      ]
    };
    
    function App() {
      const [selectedDoctor, setSelectedDoctor] = useState(null);
      const [selectedHospital, setSelectedHospital] = useState(null);
    
      const hospitalOption = item => ({ value: item.id, label: item.title });
      const hospitalOptions = () => {
        if (selectedDoctor) {
          return data.doctors
            .filter(doctor => doctor.id === selectedDoctor.value)[0]
            .hospitals.map(hospitalOption);
        } else {
          return data.hospitals.map(hospitalOption);
        }
      };
    
      const doctorOption = item => ({
        value: item.id,
        label: `Doctor ${item.name}`
      });
      const doctorOptions = () => {
        if (selectedHospital) {
          return data.doctors
            .filter(
              doctor =>
                doctor.hospitals.filter(
                  hospital => hospital.id === selectedHospital.value
                ).length
            )
            .map(doctorOption);
        } else {
          return data.doctors.map(doctorOption);
        }
      };
    
      const reset = () => {
        setSelectedDoctor(null);
        setSelectedHospital(null);
      };
    
      return (
        <div className="App">
          <h3>React-Select multi select sample</h3>
          <Select
            id="hospital"
            value={selectedHospital}
            onChange={setSelectedHospital}
            options={hospitalOptions()}
            selectedDoctor={selectedDoctor}
          />
          <Select
            id="doctor"
            value={selectedDoctor}
            options={doctorOptions()}
            onChange={setSelectedDoctor}
            selectedHospital={selectedHospital}
          />
    
          <pre selectedDoctor={selectedDoctor} selectedHospital={selectedHospital}>
            Selected Doctor: {JSON.stringify(selectedDoctor || {}, null, 2)}
            <br />
            Available Doctors: {JSON.stringify(doctorOptions() || {}, null, 2)}
          </pre>
          <pre selectedDoctor={selectedDoctor} selectedHospital={selectedHospital}>
            Selected Hospital: {JSON.stringify(selectedHospital || {}, null, 2)}
            <br />
            Available Hospitals: {JSON.stringify(hospitalOptions() || {}, null, 2)}
          </pre>
          <button onClick={reset}>Reset</button>
        </div>
      );
    }
    
    render(<App />, document.getElementById("root"));

預覽

暫無
暫無

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

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