处理来自材料UI的自动完成组件上的更改


12

我想使用Autocompletecomponent作为输入标签。我正在尝试获取标签并将它们保存在一个状态,以便以后可以将它们保存在数据库中。我在反应中使用函数而不是类。我确实尝试过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 />)} />

Answers:


26

如Yuki所述,请确保您onChange正确使用了该功能。它接收两个参数。根据文档:

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

event:回调的事件源

value:空(“自动完成”组件中的一个或多个值)。

这是一个例子:

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 },
];

非常感谢我在TextField组件上使用了onchange
Buk Lau

4

确定使用onChange正确吗?

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


非常感谢我在TextField组件上使用了onchange
Buk Lau

3

@Dworo

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

我找到了解决方法。基本上,您必须为和糟糕的Material UI 都绑定一个inputValueat 。onChageAutocompleteTextField

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 />
  )}
/>

0
  <Autocomplete
                disableClearable='true'
                disableOpenOnFocus="true"
                options={top100Films}
                getOptionLabel={option => option.title}
                onChange={this.onTagsChange}
                renderInput={params => (
                  <TextField
                    {...params}
                    variant="standard"
                    label="Favorites"
                    margin="normal"
                    fullWidth
                  />
                )}
                />

使用上面的代码后,我仍然无法获得自动完成框来显示所选的选项。


onTagsChange =(事件,值)=> {const {handleChange} = this.props; handleChange('searchKeyword',values)}
Dworo

我有完全相同的问题,从docs复制了代码,但无法正常工作。难以置信的!
德达

0

我需要在每次输入更改时都击中我的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
              />

0

当我从自动完成功能中选择一个选项时,我想更新状态。我有一个全局的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:
    }
  };
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.