【问题标题】:MUI Autocomplete filterOptioms still displaying all optionsMUI 自动完成 filterOptions 仍然显示所有选项
【发布时间】:2021-11-14 03:37:12
【问题描述】:

大家好,

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

总之;

  • 当我从 filterOptions 记录结果时,它是正确的。例如,我搜索“荷兰”,它只显示相关结果。 options.filter() 做得对。
  • 不显示此结果。自动完成功能仍会显示所有值。

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

<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,
      }}
    />
  )}
/>

【问题讨论】:

  • 你能从 filterOptions 中获得 console.log(state) 吗?
  • @Samira 当然。当我搜索Netherl 时,我会得到{inputValue: 'Netherl', getOptionLabel: ƒ} console.log 时的结果确实是值。过滤器似乎在工作,但没有渲染。

标签: javascript reactjs material-ui


【解决方案1】:

据我所知,在更改前缀后,您只更新了 value 属性。但是,除此之外,您还必须更新 inputValue 属性,它负责文本框中显示的值:

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

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

【讨论】:

    【解决方案2】:
    const [allCountries, setAllCountries] = useState([
                                                      //initial Options 
                                                     ]);
    const onChange= (inputValue )=>{
       if (inputValue === "") return options;
    
    const query = inputValue.toLowerCase();
    
    let list = options.filter((option) => {
      return `${option[1].name.toLowerCase()} (+${
        option[1].phone
      })`.includes(query);
    });
     setAllCountries(state=>(list))
    
    }
    

    自动完成道具:

    onChange={(e, value) => onChange(value)}
    

    【讨论】:

    • 好吧,inputValue 是它自己的 dearch 选项的内部值。这不是最终值。如果这是问题,结果怎么可能仍然正确?结果是正确的,只是没有正确渲染。
    • 我想我能理解你的问题,我改变了答案。你需要使用 onChange 因为那会渲染
    猜你喜欢
    • 2021-12-05
    • 1970-01-01
    • 2023-01-31
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    • 2022-11-30
    • 2021-10-08
    相关资源
    最近更新 更多