反应 Select 控制

React Select Control

我在名为 GlobalState.js 的文件中有数据,我正在尝试访问另一个名为 AddClass.js.

的文件

GlobalState.js

myclasses:[
     {
      "id":"class1",
      "name":"Maths",
      "students":["arun1","ashok1","rajesh1","mahesh1"],
      "teachers":["ramesh1","suresh1","ashwin1"]
     },
     {
      "id":"class2",
      "name":"Science",
      "students":["arun2","ashok2","rajesh2","mahesh2"],
      "teachers":["ramesh2","suresh2","ashwin2"]
    }
   ]

我想让学生的名字显示在我的 React-Select 控件上。下面是我试过的代码。谢谢支持

AddClass.js

import React, {useState, useEffect, useContext } from 'react'
import { GlobalContext } from '../../context/GlobalState'
import { v4 as uuid } from "uuid";
import { useForm } from "react-hook-form";
import { Link, useHistory } from 'react-router-dom';
import Select from 'react-select'

const AddClass = () => {
    const [selectedOption, setSelectedOption] = React.useState();
    const { addClass, myclasses} = useContext(GlobalContext);
    const studOptions = myclasses.map((c)=> {
        return {label:c.students.map((s)=>{
            console.log("s",s)
            return([{value: s, label:s}]);
        }), value:c.id}
    })

    return (
        <React.Fragment>                                
            <form onSubmit={handleSubmit(onSubmit)}>                                                                          
              <label>Select Students</label>                                  
              <Select        
                  value={selectedOption}
                  isMulti
                  onChange={handleChange}
                  options={filteredStud}                              
              />                                                                     
            </form>
        </React.Fragment>
    )
}

export default AddClass

要让所有 类 的学生加入一个 select 选项,您的代码应该执行如下操作:

const options = myclasses.map(c => c.students).flat().map(s => ({ label: s, value: s}))

我会让 studOptions 成为一个状态,从 myclasses 中提取数据填充到 studOptions,然后将其显示到 select。 示例:https://codesandbox.io/s/affectionate-liskov-5k6l4?file=/src/App.js