首页 > 解决方案 > 关注输入中的最后一个符号,但不在可见区域中

问题描述

要查看问题,您需要在输入中键入“ATW”。

问题是,当我按 Enter 并更改输入值 => 粘贴字符串的最后一个符号不在输入的可见区域中,直到我继续输入。

输入中粘贴的字符串是“All The Web, Around The Web, All The Way, At The Weekend”。

现在我看到https://ibb.co/C5KVcGk,但我期待https://ibb.co/6Jd3rrQ

如何解决?

我使用此代码创建沙箱以进行尝试。 https://codepen.io/anon/pen/exadEy?editors=1010

class Input extends React.Component {
  state = {
    value: '',
    changeValue: ''
  }

  handleChange = (e) => {
    this.setState({
      value: e.target.value,
      changeValue: e.target.value === 'ATW' 
        ? 'All The Web, Around The Web, All The Way, At The Weekend'
        : ''
    });
  }

  handleKeyDown = (e) => {
    if (e.key === "Enter") {
      e.preventDefault();
      if (this.state.changeValue) {

        return this.setState({
          value: this.state.value.replace(
              this.state.value,
              this.state.changeValue
            ),
          changeValue: ''
        })   
      }

    }
  }

  render() {
    return (
      <React.Fragment>
        <p></p>
        <input
          type="text"
          placeholder="Type ATW"
          ref={input => this.messageInput = input}
          value={this.state.value}
          onKeyDown={this.handleKeyDown}
          onChange={this.handleChange} />

        {this.state.changeValue && 
          <span>Press Enter to confirm changes: "{this.state.changeValue}"</span>
        }
      </React.Fragment>
    );
  }
}

ReactDOM.render(
  <Input />,
  document.getElementById('app')
);

标签: javascriptreactjs

解决方案


也许你必须看看这个函数

事实是光标被重置到输入中的初始位置......你必须让它结束


推荐阅读