17

I have an Autocomplete field which uses:

searchText = {this.state.searchText}

like this;

<AutoComplete
  floatingLabelText='agent input'
  ref='agentInput'
  hintText="type response"
  multiLine = {true}
  fullWidth = {true}
  searchText = {this.state.searchText}
  onNewRequest={this.sendAgentInput}
  dataSource={this.agentCommands}
/>

But when I update the this.setState({searchText: null }) it will clear the autoComplete once, but not the second time.

Not sure if this is a bug or if there's another way to reset the field.

I also tried looking for the field and adding a ref but no luck.

Filed here in case it's a bug https://github.com/callemall/material-ui/issues/2615

4

3 回答 3

21

还尝试在每次输入更新时更改searchText :

onUpdateInput={this.handleUpdateInput}

每当用户更改输入时,此函数应更改searchText :

handleUpdateInput(text) {
  this.setState({
    searchText: text
  })
}

我的代码如下(ES6):

class MyComponent extends Component {
  constructor (props) {
    super(props)

    this.dataSource = ['a', 'b' ,'c']
    this.state = {
        searchText: ''
    }

  }

  handleUpdateInput (t) { this.setState({ searchText: t }) }

  handleSelect (t) { this.setState( { searchText: '' }) }

  render () {
    return <AutoComplete dataSource={this.dataSource}
                         searchText={this.state.searchText}
                         onNewRequest={this.handleSelect.bind(this)}
                         onUpdateInput={this.handleUpdateInput.bind(this)}
    />
  }      
}

在这里,我想在用户按下回车键或从列表中选择某些项目时清除输入(因此我清除了handleSelect中的searchText),但我也在每次输入更新(handleUpdateInput )时更改了searchText的状态。

我希望它对你有用!

于 2016-01-30T09:24:46.307 回答
1

尝试这个 :

this.setState({ searchText: "\r" });

因为我认为该函数应该测试字符串的长度(BUG?)

于 2017-09-07T10:07:42.097 回答
0

对于freesoloAutocomplete,您可以根据需要控制inputValueofAutocomplete并将其设置为空字符串:

const [inputValue, setInputValue] = React.useState('');

return (
  <>
    <Button onClick={() => setInputValue('')}>clear input</Button>
    <Autocomplete
      freeSolo
      inputValue={inputValue}
      onInputChange={(_, v) => setInputValue(v)}
      options={top100Films}
      renderInput={(params) => <TextField {...params} label="Movie" />}
    />
  </>
);

如果你还想改变当前选中的值,而不仅仅是输入框中的值:

const [inputValue, setInputValue] = React.useState('');
const [value, setValue] = React.useState(null);

return (
  <>
    <Button
      onClick={() => {
        setInputValue('');
        setValue(null);
      }}
    >
      clear input
    </Button>
    <Autocomplete
      freeSolo
      value={value}
      onChange={(_, v) => setValue(v)}
      inputValue={inputValue}
      onInputChange={(_, v) => setInputValue(v)}
      options={top100Films}
      renderInput={(params) => <TextField {...params} label="Movie" />}
    />
  </>
);

Codesandbox 演示

于 2021-11-02T03:06:37.670 回答