反应自动完成多个建议

react-autocomplete multiple suggestions

  const getSuggestions = value => {
    const inputValue = value.trim().toLowerCase();
    const inputLength = inputValue.length;

    return inputLength === 0 ? [] : _products.filter(lang =>
      lang.name.toLowerCase().slice(0, inputLength) === inputValue
    );
  };

react-autocomplete 目前的算法只能找到一个阶段的第一个单词。 例如,我写"coc"或"coca"时只能找到"Coca Cola Zero Sugar Cola",但如果我写"Cola"、"Zero"或"Sugar"就找不到了.我在回购问题中询问但无法得到和回答。我试过自己没有成功。 我怎样才能编写像我上面解释的那样工作的算法?

如果您将过滤器修改为使用 .includes 而不是 ===,它将 return 多个建议:

const getSuggestions = value => {
    const inputValue = value.trim().toLowerCase();
    const inputLength = inputValue.length;

    return inputLength === 0 ? [] : _products.filter(lang =>
      lang.name.toLowerCase().includes(inputValue)
   );
 };

这也行

  const getSuggestions = value => {
    const inputValue = value.trim().toLowerCase();
    const inputLength = inputValue.length;
    return inputLength === 0 ? [] : _products.filter(lang =>
      lang.name.toLowerCase().indexOf(inputValue.toLowerCase()) > -1
    );
  };