在输入反应中选择自动填充的文本

时间:2018-06-26 20:28:34

标签: javascript string reactjs input

我在React网站上有一个输入。它具有自动填充功能。我想在输入中选择文本的自动填充部分,就像您在google中键入内容时一样。运行我的代码(如下提供)时,当我键入'do'时,它会自动填充'Dog Walking',但什么也没有选择,然后如果按Backspace键,它将删除最后一个字母,然后选择文本的自动填充部分。我的问题是:为什么在按退格键之前未选择文本?


输入:

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

1 个答案:

答案 0 :(得分:0)

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

componentDidUpdate() {
    const input = document.getElementById('search-input');
    input.focus();
    input.selectionStart = this.state.selection.selectionStart;
    input.selectionEnd = this.state.selection.selectionEnd;
}