ReactJS-材质UI自动完成功能,可动态过滤选项

时间:2020-02-02 18:39:26

标签: javascript reactjs autocomplete material-ui

我正在使用ReactJS,我使用Material UI Autocomplete创建了一个组件,在其中我需要根据选择过滤结果。如您所见,该对象具有“组”,一旦用户选择了任何选项,我就需要从显示列表中删除整个组。如果选择“地区”或“亚洲(地区)”,则需要过滤所有具有“ RG”组的对象,并在删除所选值后恢复过滤后的对象。预先感谢。

const Typeahead = props => {
    const classes = useStyles();
    let Dictionary = React.useState([]);
    const MainDictionary = [
      { NAME: "Region", FIELD: "RG" , GROUP: "RG"},
      { NAME: "Asia (Region)", FIELD: "RG-Asia" , GROUP: "RG"},
      { NAME: "Australia (Region)", FIELD: "RG-Australia" , GROUP: "RG"},
      { NAME: "Central America (Region)", FIELD: "RG-Central America" , GROUP: "RG"},
      { NAME: "Europe (Region)", FIELD: "RG-Eastern Europe" , GROUP: "RG"},
      { NAME: "Country", FIELD: "CY" , GROUP: "CY"},
      { NAME: "Country 1 (Country)", FIELD: "SC-Country 1" , GROUP: "CY"},
      { NAME: "Country 2 (Country)", FIELD: "SC-Country 2" , GROUP: "CY"},
      { NAME: "Country 3 (Country)", FIELD: "SC-Country 3" , GROUP: "CY"},
      { NAME: "Country 4 (Country)", FIELD: "SC-Country 4" , GROUP: "CY"},
      { NAME: "Country 5 (Country)", FIELD: "SC-Country 5" , GROUP: "CY"}
    ];
    Dictionary = MainDictionary;

    function filterOptions(event, params) {
      Dictionary = MainDictionary;
      params.forEach(element => {
        Dictionary = Dictionary.filter(b => {
          return b.GROUP !== element.GROUP;
        }).map(a => {
          return a;
        });
      });
    }

    return (
        <div className={classes.root}>
            <Autocomplete
                multiple
                id="tags-standard"
                width="auto"
                options={Dictionary}
                getOptionLabel={option => option.NAME}
                onChange={(event, newValue) => {
                    filterOptions(event, newValue);
                }}
                value = {selectedValue}
                renderInput={params => (
                <TextField
                    {...params}
                    variant="standard"
                    placeholder="Select From Dictionary"
                    fullWidth
                />
                )}
                renderOption={(option, { inputValue }) => {
                const matches = match(option.NAME, inputValue);
                const parts = parse(option.NAME, matches);

                return (
                    <div>
                    {parts.map((part, index) => (
                        <span
                        key={index}
                        style={{ color: part.highlight? "#36a5f7": "" , fontWeight: part.highlight ? 700 : 400 }}
                        >
                        {part.text}
                        </span>
                    ))}
                    </div>
                );
                }}
            />
        </div>
    );
};

0 个答案:

没有答案