te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - React Creating Dynamic Select and Option Elements with Material-UI - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React Creating Dynamic Select and Option Elements with Material-UI - Stack Overflow

programmeradmin4浏览0评论

So, I honestly thought this would take me 15 minutes, but I'm up around 5 hours right now. What's bothering me so much is that I know it's a simple solution, and I've tried a few different approaches as well.

I have a React App, and inside the Diagnosis Component, I have two dropdown elements that allow users to choose the Make and Model of their appliance. What I'm trying to do is allow the user to choose which Make they have, and when the make dropdown is selected, the models dropdown populates automatically.

Here is my MakeandModel.js file:

import React, { useState, useEffect } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import FormControl from '@material-ui/core/FormControl';
import InputLabel from '@material-ui/core/InputLabel';
import Select from '@material-ui/core/Select';
import MenuItem from '@material-ui/core/MenuItem';

import makeandmodel_DATA from './makeandmodel_DATA';

const useStyles = makeStyles((theme) => ({
    formControl: {
      margin: theme.spacing(1),
      minWidth: 120,
    },
    selectEmpty: {
      marginTop: theme.spacing(2),
    },
}));

console.log(makeandmodel_DATA);

export default () => {
    const classes = useStyles();
    const [data, setData] = useState();
    const [make, setMake] = useState('');
    const [model, setModel] = useState('');

    useEffect(() => {
        
    });

    const handleMakeChange = (event) => (
        setMake(event.target.value)
    );

    const handleModelChange = (event) => (
        setModel(event.target.value)
    );

    return (
        <>
            <FormControl variant="outlined" className={classes.formControl}>
                <InputLabel id="demo-simple-select-outlined-label">Make</InputLabel>
                <Select
                    labelId="demo-simple-select-outlined-label"
                    id="demo-simple-select-outlined"
                    value={make}
                    onChange={handleMakeChange}
                    label="Make"
                >
                    <MenuItem value="">
                        <em>Choose a Make</em>
                    </MenuItem>
                    {makeandmodel_DATA.map((make, index) => (
                        <MenuItem key={index} value={make.name}>{make.name}</MenuItem>
                    ))}
                </Select>
            </FormControl>

            <FormControl variant="outlined" className={classes.formControl}>
                <InputLabel id="demo-simple-select-outlined-label">Model</InputLabel>
                <Select
                    labelId="demo-simple-select-outlined-label"
                    id="demo-simple-select-outlined"
                    value={model}
                    onChange={handleModelChange}
                    label="Model"
                >
                    <MenuItem value="">
                        <em>Choose a Model</em>
                    </MenuItem>
                    
                </Select>
            </FormControl>
            <br />
       </>
    );
};

I also have some sample data I'm importing to try to populate my Make and Model dropdowns. Here is the code from the makeandmodel_DATA.json file:

[
    {
        "name": "Dyson",
        "models": [
            {
                "name": "v12"
            },
            {
                "name": "v10"
            },
            {
                "name": "ball"
            }
        ]
    },
    {
        "name": "Oreck",
        "models": [
            {
                "name": "Upright"
            },
            {
                "name": "Unique"
            },
            {
                "name": "XL"
            }
        ]
    },
    {
        "name": "Electrolux",
        "models": [
            {
                "name": "Classic"
            },
            {
                "name": "Vintage"
            },
            {
                "name": "New School"
            }
        ]
    },
    {
        "name": "Kirby",
        "models": [
            {
                "name": "Heavy"
            },
            {
                "name": "Light"
            },
            {
                "name": "Regular"
            }
        ]
    },
    {
        "name": "Hoover",
        "models": [
            {
                "name": "Windtunnel"
            },
            {
                "name": "Back"
            },
            {
                "name": "Upright"
            }
        ]
    }
]

I've tried to map over the imported data, but every time I do that to find the models, I end up returning undefined.

I've also tried to wire up the useEffect function, but couldn't figure out exactly to wire it up correctly that way either.

Like I said, I feel like the solution is super simple, but I'm overlooking something fundamental. I'm really just looking for a super simple solution that looks clean and works well. If you need any other information to help us solve this problem, just ask.

Thanks in advance!

So, I honestly thought this would take me 15 minutes, but I'm up around 5 hours right now. What's bothering me so much is that I know it's a simple solution, and I've tried a few different approaches as well.

I have a React App, and inside the Diagnosis Component, I have two dropdown elements that allow users to choose the Make and Model of their appliance. What I'm trying to do is allow the user to choose which Make they have, and when the make dropdown is selected, the models dropdown populates automatically.

Here is my MakeandModel.js file:

import React, { useState, useEffect } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import FormControl from '@material-ui/core/FormControl';
import InputLabel from '@material-ui/core/InputLabel';
import Select from '@material-ui/core/Select';
import MenuItem from '@material-ui/core/MenuItem';

import makeandmodel_DATA from './makeandmodel_DATA';

const useStyles = makeStyles((theme) => ({
    formControl: {
      margin: theme.spacing(1),
      minWidth: 120,
    },
    selectEmpty: {
      marginTop: theme.spacing(2),
    },
}));

console.log(makeandmodel_DATA);

export default () => {
    const classes = useStyles();
    const [data, setData] = useState();
    const [make, setMake] = useState('');
    const [model, setModel] = useState('');

    useEffect(() => {
        
    });

    const handleMakeChange = (event) => (
        setMake(event.target.value)
    );

    const handleModelChange = (event) => (
        setModel(event.target.value)
    );

    return (
        <>
            <FormControl variant="outlined" className={classes.formControl}>
                <InputLabel id="demo-simple-select-outlined-label">Make</InputLabel>
                <Select
                    labelId="demo-simple-select-outlined-label"
                    id="demo-simple-select-outlined"
                    value={make}
                    onChange={handleMakeChange}
                    label="Make"
                >
                    <MenuItem value="">
                        <em>Choose a Make</em>
                    </MenuItem>
                    {makeandmodel_DATA.map((make, index) => (
                        <MenuItem key={index} value={make.name}>{make.name}</MenuItem>
                    ))}
                </Select>
            </FormControl>

            <FormControl variant="outlined" className={classes.formControl}>
                <InputLabel id="demo-simple-select-outlined-label">Model</InputLabel>
                <Select
                    labelId="demo-simple-select-outlined-label"
                    id="demo-simple-select-outlined"
                    value={model}
                    onChange={handleModelChange}
                    label="Model"
                >
                    <MenuItem value="">
                        <em>Choose a Model</em>
                    </MenuItem>
                    
                </Select>
            </FormControl>
            <br />
       </>
    );
};

I also have some sample data I'm importing to try to populate my Make and Model dropdowns. Here is the code from the makeandmodel_DATA.json file:

[
    {
        "name": "Dyson",
        "models": [
            {
                "name": "v12"
            },
            {
                "name": "v10"
            },
            {
                "name": "ball"
            }
        ]
    },
    {
        "name": "Oreck",
        "models": [
            {
                "name": "Upright"
            },
            {
                "name": "Unique"
            },
            {
                "name": "XL"
            }
        ]
    },
    {
        "name": "Electrolux",
        "models": [
            {
                "name": "Classic"
            },
            {
                "name": "Vintage"
            },
            {
                "name": "New School"
            }
        ]
    },
    {
        "name": "Kirby",
        "models": [
            {
                "name": "Heavy"
            },
            {
                "name": "Light"
            },
            {
                "name": "Regular"
            }
        ]
    },
    {
        "name": "Hoover",
        "models": [
            {
                "name": "Windtunnel"
            },
            {
                "name": "Back"
            },
            {
                "name": "Upright"
            }
        ]
    }
]

I've tried to map over the imported data, but every time I do that to find the models, I end up returning undefined.

I've also tried to wire up the useEffect function, but couldn't figure out exactly to wire it up correctly that way either.

Like I said, I feel like the solution is super simple, but I'm overlooking something fundamental. I'm really just looking for a super simple solution that looks clean and works well. If you need any other information to help us solve this problem, just ask.

Thanks in advance!

Share Improve this question asked Jan 27, 2021 at 20:40 JimJim 1031 gold badge2 silver badges8 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

The best practice here is to create an object where you save your models by the Make name.

const models = React.useMemo(() => {
  const modelsValues = {};
  makeandmodel_DATA.forEach(({ name, models }) => {
    modelsValues[name] = models;
  })

 return modelsValues;
})

You only need to save the model name as you are doing it. Then you need to access to the selected Make models, and finally your Make select is gonna be something like this:

         {make && <FormControl variant="outlined" className={classes.formControl}>
            <InputLabel id="demo-simple-select-outlined-label">Model</InputLabel>
            <Select
                labelId="demo-simple-select-outlined-label"
                id="demo-simple-select-outlined"
                value={model}
                onChange={handleModelChange}
                label="Model"
            >
                <MenuItem value="">
                    <em>Choose a Model</em>
                </MenuItem>
              {models[make] ? models[make].map(model=> {
                // Here goes your models option
                return <MenuItem value="">
                    <em>Choose a Model</em>
                </MenuItem>
                }) : null
               }
            </Select>
        </FormControl>}

Maybe I have a typo but If you could give me a sandbox this can be more simple to fix.

That's a great solution!

I did the same exact thing, and I added an index to the map function to add a key to each MenuItem and set the value attribute and child on each MenuItem to model.name

{make && <FormControl variant="outlined" className={classes.formControl}>
         <InputLabel id="demo-simple-select-outlined-label">Model</InputLabel>
         <Select
             labelId="demo-simple-select-outlined-label"
             id="demo-simple-select-outlined"
             value={model}
             onChange={handleModelChange}
             label="Model"
         >
             <MenuItem value="">
                 <em>Choose a Model</em>
             </MenuItem>
             {models[make] 
                 ? models[make].map((model, index) => (
                     <MenuItem key={index} value={model.name}>{model.name}</MenuItem>
                 ))
                 : null
             }
    

     </Select>
</FormControl>}

A template you can use for when using dynamic select in material UI

                  <Select
                    displayEmpty
                    {...register('productName', { required: 'Product Name is required' })}
                    renderValue={(selected) => {
                        if (!selected || selected.length === 0) {
                            return <em disabled>Choose product</em>;
                        } else {
                            return typeof selected === 'string' ? selected?.trim() : selected;
                        }
                    }}
                    MenuProps={{
                        PaperProps: {
                            style: {
                                maxHeight: 48 * 4.5 + 8,
                                // width: '100%',
                            },
                        },
                    }}
                    fullWidth>
                    {productsData.length === 0 ? (
                        <MenuItem disabled value=''>
                            <em>None</em>
                        </MenuItem>
                    ) : (
                        productsData.map((product) => {
                            return (
                                <MenuItem key={product.id} value={product.name}>
                                    {product.name}
                                </MenuItem>
                            );
                        })
                    )}
                </Select>
发布评论

评论列表(0)

  1. 暂无评论