如何使用带有自动完成功能的 onchange material ui?

How to use onchange with autocomplete material ui?

使用 handleChange 方法处理 Form Input with Hooks 样式的 OnChange 事件,设置对象的状态。

handleChange 函数依次调用 setLocation,它使用新值更新位置状态。

为了使用户数据输入更容易,我决定将城市字段更改为自动完成,但我未能捕获自动完成的值。 在文档中他告诉我,我需要传递两个参数,但我不太理解

function(event: object, value: any) => void
event: The event source of the callback
value: null

如何访问字段的值并将其放入我的函数以插入数据?

        <Autocomplete
        style={{ width: 300 }}
        value={location.City}
        onChange={handleChange}
        options={list.City}
        classes={{
          option: classes.option,
        }}
        autoHighlight
        getOptionLabel={option => typeof option === 'string' ? option : option.City}
        renderOption={option => (
          <React.Fragment>

            {option.City} -{option.State}
          </React.Fragment>
        )}

         renderInput={params => (
           <TextField {...params} label="City"  value={location.City}  margin="normal" variant="outlined" style={{ width: 220 }} inputProps={{
             ...params.inputProps,
             autoComplete: 'disabled', // disable autocomplete and autofill
           }}/>
         )}
       />

如果您只是想在用户键入时获取输入值,则需要使用 onInputChangeonChange 处理程序在用户从下拉列表中选择一个选项时运行。

export default function ComboBox() {
  function handleInputChange(event, value) {
    console.log(value);
  }

  return (
    <Autocomplete
      id="combo-box-demo"
      options={top100Films}
      getOptionLabel={(option: FilmOptionType) => option.title}
      style={{ width: 300 }}
      onInputChange={handleInputChange}
      renderInput={params => (
        <TextField {...params} label="Combo box" variant="outlined" fullWidth />
      )}
    />
  );
}

Codesandbox

react SyntheticEvent在异步请求中设置null target,尝试使用

event.persist()

关于活动

https://reactjs.org/docs/events.html#event-pooling

 const handleOnChangeText=(event)=> {     
    event.persist();
    console.log(event)    
    let active = true;
    setOpen(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]) as CountryType[]);
      }
      active = false;
    })();   
}



<Autocomplete
      id="comboboxAsync"
      disableOpenOnFocus
      style={{ width: 300 }}
      open={open}
      onInputChange={handleOnChangeText}
...

您可以使用 mui-autocomplete npm,它简单且编码更少,选项更多(如头像视图异步调用)。您应该尝试一下。这是更多信息的示例,请访问此处。 [http://mui-autocomplete.com/home]

`import React from 'react';
 import MuiAutocomplete from 'mui-autocomplete';
 const cities = [
 {
   id: 1,
   name: "Alabama",
   code: "AL"
 },
 {
   id: 2,
   name: "Alaska",
   code: "AK"
 },
 {
   id: 3,
   name: "American Samoa",
   code: "AS"
 }];
 function Home () {
   return (
     <div>
      <MuiAutocomplete
       placeholder="Countries"
       name="countries"
       setvalue={1}
       setdata={cities}
       variant="outlined"
       template={{
        title: 'name'
       }}
      />
    </div>
    );
 }`

在这种模式下检索 ID:id-option-numberOfOption,这就是为什么我必须拆分检索到的值以更新状态

const handleAutoCompleteChange = (event, value) => {
          this.setState({ ...this.state, [event.target.id.split("-")[0]]: value });
          console.log([event.target.id.split("-")[0]],value);
}