【问题标题】:How can I load multi select dynamically? [react-select]如何动态加载多选? [反应选择]
【发布时间】:2019-12-31 06:19:16
【问题描述】:

如何动态加载多选? 我使用 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>

请帮我解决这个问题

【问题讨论】:

    标签: reactjs multi-select react-select


    【解决方案1】:

    react-select 有 options 属性。

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

    【讨论】:

    • 完美,但我怎样才能让那些选定的选项进入状态?
    • 更新了答案。您可以查看相关文档。 react-select.com/props
    • 完美运行
    • 如何根据另一个选择组件选择这个多选的值?
    【解决方案2】:

    如何根据另一个选择来选择这个多选的值 组件?

    您可以为状态中的选择和基于所选值的过滤选项存储所选值。

    我添加了带有 2 个依赖选择的快速样本 - 医院(可以有少数医生)和医生(可以在少数医院工作)。

    当您选择某些医生时 - 医院选择会更新,反之亦然。

    Preview this code

        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"));
    

    【讨论】:

      猜你喜欢
      • 2012-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-14
      • 1970-01-01
      • 2021-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多