【问题标题】:How to use onchange with autocomplete material ui?如何将 onchange 与自动完成材料 ui 一起使用?
【发布时间】:2020-04-03 02:29:23
【问题描述】:

使用handleChange 方法处理带有Hooks 样式的Form Input 的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
           }}/>
         )}
       />

【问题讨论】:

  • 好吧,我有好消息和坏消息要告诉你,好消息是我遇到了同样的问题并且不知道发生了什么,坏消息是我也没有解决它。如果你和我有同样的问题:你的自动完成与 axios/async 混淆。如果它与我的问题相同,则每次按下键时都必须以某种方式清除 axios 抱歉,我无法给出正确的答案,但也许会有所帮助!明天我会在这里检查你,也许有人可以帮助你并帮助我解决我的问题;)

标签: reactjs autocomplete material-ui react-hooks


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    react SyntheticEvent 在异步请求中设置空目标,尝试使用

    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}
    ...
    

    【讨论】:

      【解决方案3】:

      在这种模式下检索 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);
      }
      

      【讨论】:

        【解决方案4】:

        您可以使用 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>
            );
         }`
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-08-09
          • 2020-10-20
          • 2020-10-01
          • 2020-07-27
          • 2017-09-28
          • 1970-01-01
          • 2020-07-07
          相关资源
          最近更新 更多