0

我在我的 React 网站上有一个输入。它具有自动填充功能。我想在输入中选择自动填充的部分文本,就像您在谷歌中输入内容时发生的那样。运行我的代码(在下面提供)时,当我键入“do”时,它会自动填充“dog walk”,但什么都不选择,然后如果我按退格键,它会删除最后一个字母,然后选择文本的自动填充部分。我的问题是:为什么在按退格键之前没有选择文本?


输入:

<input
        type={'text'}
        placeholder={'Search'}
        name={'search'}
        onChange={this.onChange}
        value={this.state.searchTitle}
        style={{
          paddingLeft: 16,
          width: '100%',
          fontFamily: 'tbc',
          marginBottom: 5,
          borderWidth: 0,
        }}
        id={'search-input'}
/>

初始状态:

state = {
    searchTitle: '',
    suggestions: fakeServices,
    showSuggestions: false,
    selection: {
      selectionStart: 0,
      selectionEnd: 0
    },
};

更改文本时调用的函数:

onChange = (event) => {
    const text = event.target.value;
    const prevTextLength = this.state.searchTitle.length;

    this.setState({
      searchTitle: text,
      selection: {
        selectionStart: 0,
        selectionEnd: 0
      }
    });

    // Searching for suggestions and placing them into the state 
    if (text !== '') {
      const filteredServices = fuse.search(text);
      this.setState({
        showSuggestions: true,
        suggestions: filteredServices,
      });
    } else {
      this.setState({
        showSuggestions: false,
      })
    }

    if (this.state.suggestions.length !== 0 && text.length > prevTextLength) {
      this.setState({
        searchTitle: this.state.suggestions[0].title,
        selection: {
          selectionStart: text.length,
          selectionEnd: this.state.suggestions[0].title.length
        }
      });
    }

    const input = document.getElementById('search-input');

    input.focus();
    input.selectionStart = this.state.selection.selectionStart;
    input.selectionEnd = this.state.selection.selectionEnd;
};
4

1 回答 1

0

事实证明,该文本将被选中,但在该组件更新并且选择消失之后。解决方案是将负责选择的代码放在 componentDidUpdate() 生命周期函数中:

componentDidUpdate() {
    const input = document.getElementById('search-input');
    input.focus();
    input.selectionStart = this.state.selection.selectionStart;
    input.selectionEnd = this.state.selection.selectionEnd;
}
于 2018-06-26T21:11:25.640 回答