小编ofh*_*use的帖子

使用 react 更改文本输入的焦点

我的目标是创建一个表单,当您按回车键时,它会将您切换到下一个输入元素,并在您进行最后一个输入时提交表单。

这是为移动设备构建的,因为在浏览器中没有使用“下一步”按钮而不是“转到键盘”按钮的选项(有关此问题的更多信息,请参阅此答案)。

为了更好地形象化这一点,这里有一张图片:在此处输入图片说明

我也写了一些代码,但这里的重点是我无法在正确的位置捕获事件,因此表单在返回后立即提交或当我阻止事件时,焦点在我点击后发生变化返回2次。

请参阅此处的示例:https : //codepen.io/ofhouse/pen/Rgwzxy(我也粘贴了下面的代码)

class TextInput extends React.Component {
  constructor(props) {
    super(props);
    this._onKeyPress = this._onKeyPress.bind(this);
  }

  componentDidMount() {
    if (this.props.focus) {
      this.textInput.focus();
    }
  }

  componentDidUpdate(nextProps) {
    if (nextProps.focus) {
      this.textInput.focus();
    }
  }

  _onKeyPress(e) {
    if (e.key === 'Enter') {
      this.props.onSubmit(e);
    }
  }

  render() {
    return (
      <div>
        <input
          type="text"
          onKeyPress={this._onKeyPress}
          ref={input => {
            this.textInput = input;
          }}
        />
      </div>
    );
  }
}

class Application extends React.Component {
  constructor(props) {
    super(props);

    this.state …
Run Code Online (Sandbox Code Playgroud)

javascript dom-events reactjs react-dom

3
推荐指数
1
解决办法
8942
查看次数

标签 统计

dom-events ×1

javascript ×1

react-dom ×1

reactjs ×1