从材料 ui 处理自动完成组件的更改

IT技术 reactjs material-ui
2021-03-28 23:53:54

我想将Autocomplete组件用于输入标签。我正在尝试获取标签并将它们保存在状态中,以便稍后将它们保存在数据库中。我在react中使用函数而不是类。我确实尝试过onChange,但没有得到任何结果。

<div style={{ width: 500 }}>
  <Autocomplete
    multiple
    options={autoComplete}
    filterSelectedOptions
    getOptionLabel={(option) => option.tags}
    renderInput={(params) => (
      <TextField
        className={classes.input}
        {...params}
        variant="outlined"
        placeholder="Favorites"
        margin="normal"
        fullWidth
      />
    )}
  />
</div>;
5个回答

正如 Yuki 已经提到的,请确保您确实onChange正确使用了该功能。它接收两个参数。根据文档:

签名function(event: object, value: any) => void

event: 回调的事件源

value: null(自动完成组件中的一个/多个值)。

下面是一个例子:

import React from 'react';
import Chip from '@material-ui/core/Chip';
import Autocomplete from '@material-ui/lab/Autocomplete';
import TextField from '@material-ui/core/TextField';

export default class Tags extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tags: []
    };
    this.onTagsChange = this.onTagsChange.bind(this);
  }

  onTagsChange = (event, values) => {
    this.setState({
      tags: values
    }, () => {
      // This will output an array of objects
      // given by Autocompelte options property.
      console.log(this.state.tags);
    });
  }

  render() {
    return (
      <div style={{ width: 500 }}>
        <Autocomplete
          multiple
          options={top100Films}
          getOptionLabel={option => option.title}
          defaultValue={[top100Films[13]]}
          onChange={this.onTagsChange}
          renderInput={params => (
            <TextField
              {...params}
              variant="standard"
              label="Multiple values"
              placeholder="Favorites"
              margin="normal"
              fullWidth
            />
          )}
        />
      </div>
    );
  }
}

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 },
  { title: "Schindler's List", year: 1993 },
  { title: 'Pulp Fiction', year: 1994 },
  { title: 'The Lord of the Rings: The Return of the King', year: 2003 },
  { title: 'The Good, the Bad and the Ugly', year: 1966 },
  { title: 'Fight Club', year: 1999 },
  { title: 'The Lord of the Rings: The Fellowship of the Ring', year: 2001 },
  { title: 'Star Wars: Episode V - The Empire Strikes Back', year: 1980 },
  { title: 'Forrest Gump', year: 1994 },
  { title: 'Inception', year: 2010 },
];
接得好!使用 values 而不是 event.target.value 解决了这个问题
2021-06-16 23:53:54

我需要在每次输入更改时点击我的 api 才能从后端获取我的标签!

如果您想在每次输入更改时获得建议的标签,请使用 Material-ui onInputChange!

this.state = {
  // labels are temp, will change every time on auto complete
  labels: [],
  // these are the ones which will be send with content
  selectedTags: [],
}
}

//to get the value on every input change
onInputChange(event,value){
console.log(value)
//response from api
.then((res) => {
      this.setState({
        labels: res
      })
    })

}

//to select input tags
onSelectTag(e, value) {
this.setState({
  selectedTags: value
})
}


            <Autocomplete
            multiple
            options={top100Films}
            getOptionLabel={option => option.title}
            onChange={this.onSelectTag} // click on the show tags
            onInputChange={this.onInputChange} //** on every input change hitting my api**
            filterSelectedOptions
            renderInput={(params) => (
              <TextField
                {...params}
                variant="standard"
                label="Multiple values"
                placeholder="Favorites"
                margin="normal"
                fullWidth
              />
您如何在下拉列表中显示在 onInputChange 函数的 API 调用中获取的选项?就我而言,除非我关闭下拉菜单并打开它,否则不会填充选项
2021-05-28 23:53:54
@Aditya 我在关闭和重新打开时遇到了同样的问题。我发现解决方案是覆盖默认的 filterOptions。尝试添加 filterOptions={(options, state) => options} 作为 <Autocomplete> 组件的道具。
2021-06-02 23:53:54

你确定你用对了onChange吗?

onChange 签名function(event: object, value: any) => void

当我从自动完成中选择一个选项时,我想更新我的状态。我有一个管理所有输入的全局 onChange 处理程序

         const {name, value } = event.target;
         setTukio({
          ...tukio,
          [name]: value,
        });

这会根据字段的名称动态更新对象。但是在自动完成时,名称返回空白。所以我将处理程序从 更改onChangeonSelect然后创建一个单独的函数来处理更改,或者在我的情况下添加一个 if 语句来检查名称是否未通过。

// This one will set state for my onSelect handler of the autocomplete 
     if (!name) {
      setTukio({
        ...tukio,
        tags: value,
      });
     } else {
      setTukio({
        ...tukio,
        [name]: value,
      });
    }

如果您只有一个自动完成功能,则上述方法有效。如果你有多个你可以传递一个像下面这样的自定义函数

<Autocomplete
    options={tags}
    getOptionLabel={option => option.tagName}
    id="tags"
    name="tags"
    autoComplete
    includeInputInList
    onSelect={(event) => handleTag(event, 'tags')}
          renderInput={(params) => <TextField {...params} hint="koo, ndama nyonya" label="Tags" margin="normal" />}
        />

// The handler 
const handleTag = ({ target }, fieldName) => {
    const { value } = target;
    switch (fieldName) {
      case 'tags':
        console.log('Value ',  value)
        // Do your stuff here
        break;
      default:
    }
  };

@Dworo

对于在“输入”字段的下拉列表中显示所选项目有问题的任何人。

我找到了一个解决方法。基本上,你必须绑定一个inputValueonChage两个AutocompleteTextField

const [input, setInput] = useState('');

<Autocomplete
  options={suggestions}
  getOptionLabel={(option) => option}
  inputValue={input}
  onChange={(e,v) => setInput(v)}
  style={{ width: 300 }}
  renderInput={(params) => (
    <TextField {...params} label="Combo box" onChange={({ target }) => setInput(target.value)} variant="outlined" fullWidth />
  )}
/>