【问题标题】:Using react-autosuggest, show all the suggestions matching the letters使用 react-autosuggest,显示所有匹配字母的建议
【发布时间】:2019-10-03 17:06:53
【问题描述】:

有没有办法在我输入第一个字母 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' 中键入第一个字母时,它应该呈现与该字母匹配的所有匹配项(术语应该匹配名字或姓氏)。 目前它只显示名字基础。

谢谢!

【问题讨论】:

    标签: reactjs react-hooks autosuggest


    【解决方案1】:

    你可以使用onSuggestionsFetchRequested prop,来实现你想要的逻辑。像这样的东西:

    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}
        ...
    

    【讨论】:

      猜你喜欢
      • 2021-05-13
      • 2015-12-18
      • 1970-01-01
      • 2020-06-28
      • 1970-01-01
      • 1970-01-01
      • 2020-04-08
      • 2012-01-07
      • 1970-01-01
      相关资源
      最近更新 更多