过滤掉粘贴上的空行?

问题描述 投票:0回答:1

我有2个场景,用于搜索框。

场景1

用户将一些数据粘贴到框中,每个新行搜索1次。

情景2

用户使用“shift + enter”输入每个搜索行以创建新行。

粘贴数据示例

1

2

3

4

5

7



8






9



10

当他们粘贴上述数据时,我想删除所有空白行。我可以通过过滤来做到这一点,但这会产生“shift + enter”无效的副作用。

  // creates how many lines text area should be
  pastedData = event => {
    var clipboardData = event.clipboardData.getData('Text');

    var count = clipboardData.split('\n').length;
    if (count > 1) {
      this.rowCount = count;
    }
  };

  @action
  onChange = event => {
    const value = event.target.value;
    const splitValues = value.split('\n');

    this.rowCount = splitValues.length;

    if(this.rowCount > 100){
       this.searchValue = splitValues.slice(0, 100).join('\n'); 
    }else {

      this.searchValue =  value;
      // if I do this instead, this will remove all empty lines but shift + enter will not work anymore.
      //this.searchValue = splitValues.filter(x => x).join('\n');
    }

  };

  @action
  onKeyDown = event => {
    if (event.key == 'Enter' && event.shiftKey) {
      // make text area bigger.
      this.rowCount = this.rowCount + 1;
    } else if (event.key == 'Enter') {
      //submit form
    }
  };

 // switches between an normal text box and textarea is more than 1 line is entered.
  {this.rowCount === 1 ? (
    <input
      autoFocus={true}
      className="input"
      type="text"
      name="searchValue"
      onPaste={this.pastedData}
      onChange={this.onChange}
      onKeyDown={this.onKeyDown}
      value={this.searchValue}
    />
  ) : (
    <textarea
      autoFocus={true}
      className="textarea"
      name="search-area"
      rows={this.rowCount}
      value={this.searchValue}
      onChange={this.onChange}
      onKeyDown={this.onKeyDown}
    />
  )}
javascript reactjs onchange mobx onkeydown
1个回答
0
投票

鉴于您希望在用户粘贴某些内容时删除新行,最好使用onPaste(而不是onChangesynthetic event provided by React,专门用于此活动。每当输入元素记录其值的变化时,onChange就会触发,无论是通过粘贴还是用户的直接输入。如果需要,您可以同时使用两者。

© www.soinside.com 2019 - 2024. All rights reserved.