Material-ui 自动完成清除值

Kir*_*ill 28 reactjs material-ui redux-form

我的反应代码中有一个问题。

我使用 Material-ui 和 redux-form。我有像这样的选择输入,在改变这个选择后,我应该在 . 我使用 react-form 中的 action 'change' 并为 textfield 设置值。但标签 in 仍然存在。我可以清除或重置 中的值吗?

<Autocomplete
    options={list}
    getOptionLabel={option => option.name}
    onInputChange={onChange}
    onChange={onChangeAutoComplete}
    noOptionsText='??? ????????? ?????????'
    loadingText='????????...'
    openText='???????'
    renderInput={params => (
        <Field
            {...params}
            label={label}
            name={fieldName}
            variant="outlined"
            fullWidth
            component={renderTextField}
            className={classes.textField}
            margin="normal"
        />
    )}
/>
Run Code Online (Sandbox Code Playgroud)

小智 50

在 value 道具上使用钩子会破坏自动完成组件的功能(至少对我而言)。使用类,和设置本地状态是一样的。

幸运的是它是一个反应组件,所以它有一个“关键”道具。当 key 属性发生变化时,组件将使用默认值重新渲染(这是一个空数组,因为没有选择任何内容)。我在父组件中使用钩子并将值传递给 key 道具,只要需要重置。

<Autocomplete
    key={somethingMeaningful} // Bool, or whatever just change it to re-render the component
//...other props
/>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!

  • @theSekyi 每次我需要清除自动完成功能时,我都会随机更改密钥。我的是使用 momentJs.toStringISO() (5认同)
  • 如果您设置了默认值,则不清楚。它会重置为默认值。我需要澄清! (3认同)
  • 我认为这是一个不好的做法,因为您正在强制组件重新渲染 (3认同)

Was*_*her 10

使用value您的<Autocomplete />是这样的:

<Autocomplete
    value={this.state.value} //insert your state key here
//...other props
/>
Run Code Online (Sandbox Code Playgroud)

然后清除该键的状态,以清除自动完成字段值


Baq*_*qvi 9

我将发布一种清除自动完成值的非常肮脏的方法。仅当其他方法不起作用时才尝试;

import React, { useRef } from 'react';
...
const autoC = useRef(null);
...
<Autocomplete
  ...
  ref={autoC}
/>
Run Code Online (Sandbox Code Playgroud)

然后当你想清除该值时;

const ele = autoC.current.getElementsByClassName('MuiAutocomplete-clearIndicator')[0];
if (ele) ele.click();
Run Code Online (Sandbox Code Playgroud)

  • 显然很多人使用这种方法 - https://github.com/mui-org/material-ui/issues/4736#issuecomment-642444300 (2认同)

小智 6

材质 UI 自动完成onInputChange回调提供reason参数。如果输入已被输入更改,则原因将为input,如果您选择了选项,则原因将为reset

onInputChange={(event, newInputValue, reason) => {
    if (reason === 'reset') {
      setValue('')
      return
    } else {
      setValue(newInputValue)
    }
  }}
Run Code Online (Sandbox Code Playgroud)

setValueuseState并且您可以将值状态传递给自动完成value属性。

  • 以及如何以编程方式调用它? (2认同)

Den*_*nis 5

当选择某个项目时,您可以使用类似以下内容的方法来清除自动完成字段。

<Autocomplete
  value={null}
  blurOnSelect={true} />
Run Code Online (Sandbox Code Playgroud)

clearOnBlur={true}请注意,如果您使用该选项,您可能还需要进行设置freeSolo

来源https://mui.com/api/autocomplete/#props