首页 > 解决方案 > MUI 自动完成 filterOptions 仍然显示所有选项

问题描述

大家好,

现在有点奇怪。由于限制和其他用例,我有一个高度定制的自动完成功能。我现在有过滤器的问题。它仍在显示所有可用选项。我 console.logged 过滤结果本身,这确实有效。当我记录它时,我只看到过滤后的值。事情是,所有选项都保持显示。没有一个被过滤。

简而言之;

这里出了什么问题?我处理错了什么还是有其他事情在起作用?

<Autocomplete
  options={allCountries}
  onChange={(event, newValue) => {
    if (!newValue || !newValue[1] || !newValue[1].phone) return;

    setPrefix(newValue[1].phone);
  }}
  value={allCountries.find(
    (nestedArray) => nestedArray[1].phone === prefix
  )}
  autoHighlight
  getOptionLabel={(option) => `+${option[1].phone}`}
  renderOption={(props, option) => (
    <Box
      component="li"
      sx={{ "& > img": { mr: 2, flexShrink: 0 } }}
      {...props}
    >
      <img
        width="20"
        src={`https://flagcdn.com/w20/${option[0].toLowerCase()}.png`}
      />
      {option[1].name} (+{option[1].phone})
    </Box>
  )}
  filterOptions={(options, state) => {
    if (state.inputValue === "") return options;

    const query = state.inputValue.toLowerCase();

    return options.filter((option) => {
      return `${option[1].name.toLowerCase()} (+${
        option[1].phone
      })`.includes(query);
    });
  }}
  renderInput={(params) => (
    <TextField
      {...params}
      label="Prefix"
      inputProps={{
        ...params.inputProps,
      }}
    />
  )}
/>

标签: javascriptreactjsmaterial-ui

解决方案


据我所见,您仅在value更改前缀后才更新道具。但是,除此之外,您还必须更新inputValueprop,它负责显示在文本框中的值:

const [inputValue, setInputValue] = React.useState('');

...
    inputValue={inputValue}
    onInputChange={(event, newInputValue) => {
        setInputValue(newInputValue);
    }}
...

推荐阅读