Как очистить данные окна автозаполнения с помощью OnClick? - PullRequest
1 голос
/ 09 мая 2020

Я использовал материал UI AutoCompleteBox, вот ссылка: https://material-ui.com/components/autocomplete/

Мой код:

<Autocomplete
  open={showUniSuggs}
  onOpen={this.props.getUniversityOptions}
  onChange={(event, value) =>
    this.props.handleUniversityChange(value)
  }
  onClose={this.props.onUniversityClose}
  getOptionLabel={(option) => option._id}
  options={universityOptions}
  loading={uniLoading}
  // disabled={disableUniversity}
  renderInput={(params) => (
    <TextField
      {...params}
      label="Search for university"
      fullWidth
      variant="filled"
      margin="dense"
      InputProps={{
        ...params.InputProps,
        endAdornment: (
          <React.Fragment>
            {uniLoading ? (
              <CircularProgress color="inherit" size={20} />
            ) : null}
            {params.InputProps.endAdornment}
          </React.Fragment>
        ),
      }}
    />
  )}
/>

Каждый раз при нажатии на Панель поиска автозаполнения Вызывается API, и данные сохраняются в getUniversityOptions Выбираем любое значение, затем щелкаем крестик с Панель поиска автозаполнения , и данные очищаются. Но я хочу, чтобы эти данные очищались с помощью функции Onclick. При каждом нажатии кнопки данные очищаются. Итак, как это можно сделать.

1 Ответ

1 голос
/ 10 мая 2020

вы можете установить свойство значения с пустой строкой, чтобы очистить значение, например

<Autocomplete value={value} .....
<button onClick={() => { setValue('') }} >Clear Value</button>

вот полный пример:

import React from 'react';
import TextField from '@material-ui/core/TextField';
import Autocomplete, {createFilterOptions} from '@material-ui/lab/Autocomplete';

const filter = createFilterOptions();

export default function FreeSoloCreateOption() {
    const [value, setValue] = React.useState(null);

    return (
        <div>
            <Autocomplete
                value={value}
                onChange={(event, newValue) => {
                    // Create a new value from the user input
                    if (newValue && newValue.inputValue) {
                        setValue({
                            title: newValue.inputValue,
                        });
                        return;
                    }
                    setValue(newValue);
                }}
                filterOptions={(options, params) => {
                    const filtered = filter(options, params);

                    // Suggest the creation of a new value
                    if (params.inputValue !== '') {
                        filtered.push({
                            inputValue: params.inputValue,
                            title: `Add "${params.inputValue}"`,
                        });
                    }
                    return filtered;
                }}
                selectOnFocus
                clearOnBlur
                id="free-solo-with-text-demo"
                options={top100Films}
                getOptionLabel={(option) => {
                    // Value selected with enter, right from the input
                    if (typeof option === 'string') {
                        return option;
                    }
                    // Add "xxx" option created dynamically
                    if (option.inputValue) {
                        return option.inputValue;
                    }
                    // Regular option
                    return option.title;
                }}
                renderOption={(option) => option.title}
                style={{width: 300}}
                freeSolo
                renderInput={(params) => (
                    <TextField {...params} label="Free solo with text demo" variant="outlined"/>
                )}
            />
            <button onClick={() => { setValue('') }} >Clear Value</button>
        </div>
    );
}

// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films = [
    {title: 'The Shawshank Redemption', year: 1994},
    {title: 'The Godfather', year: 1972},
    {title: 'The Godfather: Part II', year: 1974},
    {title: 'The Dark Knight', year: 2008},
    {title: '12 Angry Men', year: 1957},
];
...