Как использовать Autosuggest в интерфейсе материалов - PullRequest
0 голосов
/ 09 марта 2019

Я пытаюсь использовать автозаполнение в интерфейсе материалов.Я устанавливаю свои собственные данные в методе componentDidMount.Есть ли правильный или лучший способ установить данные вместо передачи в качестве реквизита и установки в массиве предложений?

Вызов компонента:

<IntegrationAutosuggest  placeHolder="Search the data " data={this.state.options} onSelect={this.handleSuggestionSelected}/>

Я использую реагирование-автозаполнениепример из https://material -ui.com / demos / autocomplete / , но добавлен метод componentDidMount.

 let suggestions = [];
//     { label: 'Afghanistan' },
//     { label: 'Aland Islands' },
//     { label: 'Brunei Darussalam' },
// ];

function renderInputComponent(inputProps) {
    const { classes, inputRef = () => {}, ref, ...other } = inputProps;

    return (
        <TextField
            className={classes.textField}
            fullWidth
            variant="outlined"
            InputProps={{
                inputRef: node => {
                    ref(node);
                    inputRef(node);
                },
                classes: {
                    input: classes.input,
                },
            }}
            {...other}
        />
    );
}

function renderSuggestion(suggestion, { query, isHighlighted }) {
    const matches = match(suggestion.label, query);
    const parts = parse(suggestion.label, matches);

    return (
        <MenuItem selected={isHighlighted} component="div">
            <div>
                {parts.map((part, index) =>
                        part.highlight ? (
                            <span key={String(index)} style={{ fontWeight: 500 }}>
              {part.text}
            </span>
                        ) : (
                            <strong key={String(index)} style={{ fontWeight: 300 }}>
                                {part.text}
                            </strong>
                        ),
                )}
            </div>
        </MenuItem>
    );
}

function initSuggestions(value) {
    suggestions = value;
}

function getSuggestions(value) {
    const inputValue = deburr(value.trim()).toLowerCase();
    const inputLength = inputValue.length;
    let count = 0;

    return inputLength === 0
        ? []
        : suggestions.filter(suggestion => {
            //console.log('suggestion is:'+suggestion.label);
            //console.log(!suggestion.label);

            const keep =
                count < 5 && suggestion.label && suggestion.label.slice(0, inputLength).toLowerCase() === inputValue;

            if (keep) {
                count += 1;
            }

            return keep;
        });
}

function getSuggestionValue(suggestion) {
    return suggestion.label;
}

function onSuggestionSelected(event, { suggestion, suggestionValue, suggestionIndex, sectionIndex, method }) {
    console.log('HandleSuggestion() '+suggestionValue);
}

const styles = theme => ({
    root: {
        height: 50,
        flexGrow: 1,
    },
    container: {
        position: 'relative',
    },
    suggestionsContainerOpen: {
        position: 'absolute',
        zIndex: 998,
        marginTop: theme.spacing.unit,
        left: 0,
        right: 0,
    },
    suggestion: {
        display: 'block',
    },
    suggestionsList: {
        margin: 0,
        padding: 0,
        listStyleType: 'none',
    },
    divider: {
        height: theme.spacing.unit * 2,
    },
});

class IntegrationAutosuggest extends React.Component {
    state = {
        single: '',
        popper: '',
        suggestions: [],
    };

    componentDidMount() {
        initSuggestions(this.props.data);
    }

    handleSuggestionsFetchRequested = ({ value }) => {


        this.setState({
            suggestions: getSuggestions(value),
        });
    };

    // handleSuggestionSelected = (event, { suggestion, suggestionValue, suggestionIndex, sectionIndex, method }) => {
    //     console.log(suggestionValue + ' Selected!');
    // };

    handleSuggestionsClearRequested = () => {
        this.setState({
            suggestions: [],
        });
    };

    handleChange = name => (event, { newValue }) => {
        this.setState({
            [name]: newValue,
        });
    };

    render() {
        const { classes } = this.props;
        console.log('Re-render!!');
        console.log(this.props);
        console.log(this.state.suggestions);

        const autosuggestProps = {
            renderInputComponent,
            suggestions: this.state.suggestions,
            onSuggestionsFetchRequested: this.handleSuggestionsFetchRequested,
            onSuggestionsClearRequested: this.handleSuggestionsClearRequested,
            onSuggestionSelected: this.props.onSelect,
            getSuggestionValue,
            renderSuggestion,
        };

        return (
            <div className={classes.root}>
                <Autosuggest
                    {...autosuggestProps}
                    inputProps={{
                        classes,
                        placeholder: this.props.placeHolder,
                        value: this.state.single,
                        onChange: this.handleChange('single'),
                    }}
                    theme={{
                        container: classes.container,
                        suggestionsContainerOpen: classes.suggestionsContainerOpen,
                        suggestionsList: classes.suggestionsList,
                        suggestion: classes.suggestion,
                    }}
                    renderSuggestionsContainer={options => (
                        <Paper {...options.containerProps} square>
                            {options.children}
                        </Paper>
                    )}
                />
                <div className={classes.divider} />


            </div>
        );
    }
}

IntegrationAutosuggest.propTypes = {
    classes: PropTypes.object.isRequired,

};

export default withStyles(styles)(IntegrationAutosuggest);

1 Ответ

0 голосов
/ 09 марта 2019

Существует множество способов ... вы можете сохранить состояние suggestionList, инициализировать его как пустое и обновить его, используя fetch запросы со строкой поиска в качестве параметра.Или вы можете получить полный список всех вещей, доступных для поиска в массиве в конструкторе, а затем выполнить фильтрацию в зависимости от строки поиска.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...