首页 > 解决方案 > 从 material-ui 自动完成组合框中清除所有选定的值

问题描述

解决方案

我用renderTags在我的Autocomplete

renderTags={() => (
    <div>
        {(props.selectedAutocompleteValues).map(value => (
            <Chip key={value} label={value} />
        ))}
    </div>
)}

原始问题

我正在尝试添加一个处理程序,该处理程序从具有多个值和下拉列表的自动完成中清除所有选定的值。基本上复制自动完成内部清除按钮的操作,并从自动完成外部触发此操作。

这样做的原因是我想要一个过滤器(material-ui Select),它允许减少自动完成中的选项数量。更改过滤器值时,应清除先前选择的自动完成值。

我正在使用以下代码呈现自动完成中的值,所以看起来我需要做的是以params某种方式更改。有关如何执行此操作或清除值的其他方法的任何建议?

renderInput={params => (
    <TextField {...params} label="my-label" variant="outlined" fullWidth />
)}

Ryan Cogswell 发表评论后更新

<Autocomplete
    multiple
    disableCloseOnSelect
    autoHighlight
    clearText='Nullstill'
    closeText='Lukk'
    openText='Åpne'
    options={Array.from(props.myMap.keys())}
    onChange={(event: any, value: string) => {
        props.myUpdateFunction(value)
    }}
    renderInput={params => (
        <TextField {...params} label="myLabel" variant="outlined" fullWidth />
    )}
/>

wheremyUpdateFunction在 where 的祖父母组件中Autocomplete is

myUpdateFunction = (myArray: Array<string>) => {
    this.setState({
        selectedAutocompleteValues: myArray,
    })
}

Select我想用来重置组件的组件Autocomplete

<Select
    labelId="my-select-label"
    id="my-select"
    autoWidth
    value={props.mySelectValue}
    onChange={(event: any) => props.updateSelect(event.target.value)}>
    {Array.from(props.selectOptions, ([optionNr, optionName]) =>
        <MenuItem key={optionNr} value={optionNr}>{optionName}</MenuItem>
    )}
</Select>

使用以下 onChange 处理程序:

updateFylke = (value: number) => {
    const selectedAutocompleteValues = new Array<string>();
    this.setState({
        mySelectValue: value,
        selectedAutocompleteValues: selectedAutocompleteValues,
    })
}

标签: reactjsautocompletematerial-ui

解决方案


我建议使用受控输入方法(即为using指定value道具)。然后清除只是适当更新您的状态的问题。AutocompleteselectedAutocompleteValuesAutocomplete

您可以在此相关答案中看到此方法的示例:Material ui Autocomplete: can tags are created on events 除了“Enter”事件吗?.


推荐阅读