React JS Material UI 自动完成:更改选项

sof*_*ser 6 javascript autocomplete reactjs material-ui

我想为我的 React JS 项目使用自动完成字段。对于 UI 的设计,我使用 Material UI。在文档中您可以看到以下示例:

<Autocomplete
                    required
                    id="combo-box-demo"
                    filterOptions={(x) => x}
                    value={this.state.departure}
                    options={top100Films}
                    getOptionLabel={(option) => option.title}
                    renderInput={(params) => <TextField {...params} label="Startpunkt" variant="outlined" />}
                />
Run Code Online (Sandbox Code Playgroud)

选项对象具有以下默认值:

let top100Films = [
        { title: 'The Shawshank Redemption', year: 1994 },
        { title: 'Monty Python and the Holy Grail', year: 1975 },
    ];
Run Code Online (Sandbox Code Playgroud)

出于我的目的,我想动态更改选项,因为我使用 Rest API 来获取输入结果。因此,我的问题是如何在用户键入时动态更改选项。

小智 8

您可以在您的情况下使用 onInputChange 属性:

      <Autocomplete
            required
            id='combo-box-demo'
            filterOptions={(x) => x}
            value={this.state.departure}
            options={top100Films}
            getOptionLabel={(option) => option.title}
            onInputChange={(event: object, value: string, reason: string) => {
              if (reason === 'input') {
                changeOptionBaseOnValue(value);
              }
            }}
            renderInput={(params) => (
              <TextField {...params} label='Startpunkt' variant='outlined' />
            )}
          />
Run Code Online (Sandbox Code Playgroud)

然后您可以定义changeOptionBaseOnValue 来处理您的选项。


Kha*_*bir 0

你可以检查这个例子:

import fetch from 'cross-fetch';
import React from 'react';
import TextField from '@material-ui/core/TextField';
import Autocomplete from '@material-ui/lab/Autocomplete';
import CircularProgress from '@material-ui/core/CircularProgress';

function sleep(delay = 0) {
  return new Promise((resolve) => {
    setTimeout(resolve, delay);
  });
}

export default function Asynchronous() {
  const [open, setOpen] = React.useState(false);
  const [options, setOptions] = React.useState([]);
  const loading = open && options.length === 0;

  React.useEffect(() => {
    let active = true;

    if (!loading) {
      return undefined;
    }

    (async () => {
      const response = await fetch('https://country.register.gov.uk/records.json?page-size=5000');
      await sleep(1e3); // For demo purposes.
      const countries = await response.json();

      if (active) {
        setOptions(Object.keys(countries).map((key) => countries[key].item[0]));
      }
    })();

    return () => {
      active = false;
    };
  }, [loading]);

  React.useEffect(() => {
    if (!open) {
      setOptions([]);
    }
  }, [open]);

  return (
    <Autocomplete
      id="asynchronous-demo"
      style={{ width: 300 }}
      open={open}
      onOpen={() => {
        setOpen(true);
      }}
      onClose={() => {
        setOpen(false);
      }}
      getOptionSelected={(option, value) => option.name === value.name}
      getOptionLabel={(option) => option.name}
      options={options}
      loading={loading}
      renderInput={(params) => (
        <TextField
          {...params}
          label="Asynchronous"
          variant="outlined"
          InputProps={{
            ...params.InputProps,
            endAdornment: (
              <React.Fragment>
                {loading ? <CircularProgress color="inherit" size={20} /> : null}
                {params.InputProps.endAdornment}
              </React.Fragment>
            ),
          }}
        />
      )}
    />
  );
}
Run Code Online (Sandbox Code Playgroud)

来源

  • 这不会在输入时获取数据,这只会进行一次 api 调用来一次获取所有选项,这不是所要求的 (10认同)