簡體   English   中英

如何在反應鈎子的級聯下拉列表中將數組的第一個值設置為默認值

[英]how to set first value of array as default in cascading dropdown in react hooks

我正在使用材料 UI 列出下拉值我有一個中心、國家和帳戶下拉字段我想將數組 object 的第一個值設置為 select 初始值已選擇。

數據文件:

export const dataHub = [
    { name: 'Western Europe', hubId: 1 },
    { name: 'IMMEA', hubId: 2 },
]

export const dataCountry = [
    { name: 'France', countryId: 1, hubId: 1 },
    { name: 'Germany', countryId: 2, hubId: 1 },
    { name: 'Italy', countryId: 3, hubId: 1 },
    { name: 'Spain', countryId: 4, hubId: 1 },
    { name: 'Sweden', countryId: 5, hubId: 1 },
    { name: 'Switzerland', countryId: 6, hubId: 2 },
    { name: 'Uk', countryId: 7, hubId: 1 },
]

export const dataAccount = [
    {name:'Telco-channel',panterName:'',accountId:1,countryId:1},
    {name:'Consumer-Online',panterName:'',accountId:2,countryId:2},
    {name:'Education-Retail',panterName:'',accountId:3,countryId:2},
    {name:'Non-Trade',panterName:'',accountId:4,countryId:2},
    {name:'Telco-channel',panterName:'',accountId:5,countryId:3},
    {name:'Commercial-channel',panterName:'',accountId:6,countryId:4},
    {name:'Consumer-Retail',panterName:'',accountId:7,countryId:5},
    {name:'Commercial-Online',panterName:'',accountId:8,countryId:6},
    {name:'Non-Trade',panterName:'',accountId:9,countryId:6},
    {name:'Education-Online',panterName:'',accountId:10,countryId:1},
    {name:'Consumer-Retail',panterName:'',accountId:11,countryId:2},
    {name:'Telco-channel',panterName:'',accountId:12,countryId:2},
    {name:'Commercial-channel',panterName:'',accountId:13,countryId:3},
    {name:'Consumer-Online',panterName:'',accountId:14,countryId:3},
    {name:'Consumer-Online',panterName:'',accountId:15,countryId:4},
    {name:'Consumer-Retail',panterName:'',accountId:16,countryId:4},
    {name:'Non-Trade',panterName:'',accountId:17,countryId:4},
    {name:'Telco-channel',panterName:'',accountId:18,countryId:4},
    {name:'Consumer-Online',panterName:'',accountId:19,countryId:5},
    {name:'Commercial-Retail',panterName:'',accountId:20,countryId:7},
    {name:'Consumer-Online',panterName:'',accountId:21,countryId:7},
    {name:'Education-Online',panterName:'',accountId:22,countryId:7},
    {name:'Education-Retial',panterName:'',accountId:23,countryId:7},
    {name:'Non-Trade',panterName:'',accountId:24,countryId:7},
]

下面是組件渲染下拉字段

import React, { useState, useEffect } from 'react'
import { dataHub, dataCountry, dataAccount } from "../../constants/defaultValues";
import SelectMenu from '../../components/SelectMenu';


const defaultItemHub = { name: 'Select Hub ...' };
const defaultItemCountry = { name: 'Select Country ...' };
const defaultItemAccount = { name: 'Select Account ...' };

const Filters = () => {
    const [hub, setHub] = useState('')
    const [country, setCountry] = useState('')
    const [account, setAccount] = useState('')
    const [countries, setCountries] = useState(dataCountry)
    const [accounts, setAcconts] = useState(dataAccount)


    useEffect(() => {
const defaultHub = sort(dataHub)[0]
        
        const defaultCountry = sort(dataCountry).filter(country => country.hubId === defaultHub.hubId)[0];
        
        let defaultAccount = sort(dataAccount).filter(account => account.countryId === defaultCountry.countryId)[0];
        setHub(defaultHub)
        setCountry(defaultCountry)
        setAccount(defaultAccount)
    }, [])

    const hubChange = (event) => {
        const hub = event.target.value;
        const countries = dataCountry.filter(country => country.hubId === hub.hubId);
        setHub(hub)
        setCountries(countries)
        setCountry('')
        setAccount('')
    }

    const countryChange = (event) => {
        const country = event.target.value;
        const accounts = dataAccount.filter(account => account.countryId === country.countryId);
        setCountry(country)
        setAcconts(accounts)
        setAccount('')
    }

    const accountChange = (event) => {
        setAccount(event.target.value);
    }

    const hasHub = hub && hub !== defaultItemHub;
    const hasCountry = country && country !== defaultItemCountry;
    //console.log("defaultHub",defaultHub)
    return (
        <div className="container">
            <div className="d-flex mr-1 justify-content-center align-items-center">
                <SelectMenu field={"Hub"} value={hub} options={dataHub} fieldtype={"dropdown"} onChange={hubChange} />
                <SelectMenu field={"Country"} value={country} disabled={!hasHub} options={countries} fieldtype={"dropdown"} onChange={countryChange} />
                <SelectMenu field={"Account"} value={account} disabled={!hasCountry} options={accounts} fieldtype={"dropdown"} onChange={accountChange} />
            </div>
        </div>
    )
}
export default Filters

selectMenu 組件,我正在為下面的組件傳遞所需的道具

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';
import TextField from '@material-ui/core/TextField';
const useStyles = makeStyles((theme) => ({
    formControl: {
        margin: theme.spacing(2),
        minWidth: 180,
    },
    selectEmpty: {
        marginTop: theme.spacing(2),
    },
}));

export default function SelectMenu({ field, options, value, disabled, fieldtype, onChange }) {
    const classes = useStyles();
    
    const handleChange = (event) => {
        onChange(event)
    };
    // When the field is a dropdown
    if (fieldtype === "dropdown") {
        return (
            <div>
                <FormControl variant="outlined" className={classes.formControl}>
                    <InputLabel id="demo-simple-select-outlined-label">{field}</InputLabel>
                    <Select
                        labelId="demo-simple-select-outlined-label"
                        id="demo-simple-select-outlined"
                        value={value || ''}
                        onChange={handleChange}
                        label={field}
                        disabled={disabled}
                    >
                        {
                            options.map((element, key) => {
                                return (
                                    <MenuItem key={key} value={element}>{element.name}</MenuItem>
                                )
                            })
                        }
                    </Select>
                </FormControl>
            </div>
        );
    }
    else {
        // When the field is a Integer and Prepopulated
        if (options != null) {
            return (
                <div>
                    <FormControl variant="outlined" className={classes.formControl}>
                        <TextField
                            id="outlined-read-only-input"
                            label={field}
                            value={options[0].value}
                            defaultValue="Hello World"
                            InputProps={{
                                readOnly: true,
                            }}
                            variant="outlined"
                        />
                    </FormControl>
                </div>
            )
        }
        //When the field is a Integer and a Input from the user
        else {
            return (
                <div>
                    <FormControl variant="outlined" className={classes.formControl}>
                        <TextField id="outlined-basic"
                            onChange={handleChange}
                            label={field} variant="outlined" />
                    </FormControl>
                </div>
            )
        }

    }
}

誰能幫助我我做錯了什么,我無法在下拉列表中設置默認值。

在此處輸入圖像描述

嘗試在<Select>標記中使用defaultValue而不是value

我覺得有幾個原因可能會導致這個問題。

  1. 確保默認值應出現在實際選項中。 即默認國家應該是國家列表中的一個,然后只有默認值被材質 UI 組件選擇。
  2. 根據材料 UI 文檔If the value is an object it must have reference equality with the option in order to be selected. If the value is not an object, the string representation must match with the string representation of the option in order to be selected. If the value is an object it must have reference equality with the option in order to be selected. If the value is not an object, the string representation must match with the string representation of the option in order to be selected. 因此,您應該定義相等,以便Selectvalue屬性將與MenuItemvalue屬性匹配,然后將其選為默認值。

暫無
暫無

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

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