当从搜索栏中删除字符时,为什么我的react-autosuggest不起作用

时间:2018-03-21 22:11:52

标签: javascript reactjs

我在我的应用程序中使用react-autosuggest组件作为搜索栏。我对该组件的解释如下:

import Autosuggest from 'react-autosuggest';
import React from 'react'


export class SearchBar extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            value: '',
            suggestions: this.props.tickers
        };
    }

    onChange = (event, { newValue, method }) => {
        this.setState({
            value: newValue
        });
    };

    onSuggestionsFetchRequested = ({ value }) => {
        this.setState({
            suggestions: this.getSuggestions(value)
        });
    };

    onSuggestionsClearRequested = () => {
        this.setState({
            suggestions: this.props.tickers
        });
    };

    escapeRegexCharacters(str) {
        return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }

    getSuggestions(value) {
        const escapedValue = this.escapeRegexCharacters(value.trim());

        if (escapedValue === '') {
            return [];
        }

        const regex = new RegExp('^' + escapedValue, 'i');

        return this.state.suggestions.filter(language => regex.test(language));
    }

    getSuggestionValue(suggestion) {
        return suggestion;
    }

    renderSuggestion(suggestion) {
        return (
            <span>{suggestion}</span>
        );
    }

    render() {
        const { value, suggestions } = this.state;
        const inputProps = {
            placeholder: "Search for stocks...",
            value,
            onChange: this.onChange
        };

        return (
            <Autosuggest
                suggestions={suggestions}
                onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
                onSuggestionsClearRequested={this.onSuggestionsClearRequested}
                getSuggestionValue={this.getSuggestionValue}
                renderSuggestion={this.renderSuggestion}
                inputProps={inputProps} />
        );
    }
}

这种当前实现在最初搜索时工作正常,例如,提供字母'A'给出A的所有选项。当提供'AL'时,它进一步过滤列表以仅为'AL'提供选项。但是当我删除字符“L”时,列表不会刷新,只显示“AL”而不是A的建议。

Entering A 输入A

Entering AB 输入AB

Deleting the B from AB 从AB中删除B。

1 个答案:

答案 0 :(得分:0)

应该可以

getSuggestions(value) {
    const escapedValue = this.escapeRegexCharacters(value.trim());

    if (escapedValue === '') {
        return [];
    }

    const regex = new RegExp('^' + escapedValue, 'i');

    return this.props.tickers.filter(language => regex.test(language));
}