使用react-autosuggest,显示所有与字母匹配的建议

时间:2019-10-03 05:59:45

标签: reactjs react-hooks autosuggest

当我输入第一个字母A时,是否有一种显示建议列表的方法,它应该显示与所有A匹配的字母。 例如:我有一个学生名单,例如

 {
        "id": 1,
        "name": "Dee dee Tanser"
    },
    {
        "id": 2,
        "name": "Tobiah Stockwell"
    },
    {
        "id": 3,
        "name": "Gregorius Densham"
    },
    {
        "id": 4,
        "name": "Ursula Morrill"
    },
    {
        "id": 5,
        "name": "Josey Bainton"
    },

当用户在autosuggest's'中键入第一个字母时,它应呈现与该字母的所有匹配项(术语应与名字或姓氏匹配)。 目前,它仅显示名字依据。

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用onSuggestionsFetchRequested属性来实现所需的逻辑。像这样:

const students = [
  {
      "id": 1,
      "name": "Dee dee Tanser"
  },
  {
      "id": 2,
      "name": "Tobiah Stockwell"
  },
];

// Teach Autosuggest how to calculate suggestions for any given input value.
getSuggestions = value => {
    const inputValue = value.trim().toLowerCase();
    const inputLength = inputValue.length;

    if (inputLength === 0) {
        return [];
    }

    return students.filter(student => {
        return student.name.split(' ').some(term => {
            return term.toLowerCase().slice(0, inputLength) === inputValue;
        })
    });
};

  // Autosuggest will call this function every time you need to update suggestions.
  onSuggestionsFetchRequested = ({ value }) => {
    this.setState({
      suggestions: this.getSuggestions(value)
    });
  };

 <Autosuggest
    suggestions={suggestions}
    onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
    ...