按下输入React.js时,请关注下一个字段

Gui*_*rmo 13 javascript reactjs

当我使用React.js单击输入时,我想找到一种方法来关注下一个字段

  @autobind
  handleKeyPress(event){
    if(event.key === 'Enter'){
      this.refs.email.focus();
    }
  }

  @autobind
  handleKeyPressEmail(event){
    if(event.key === 'Enter'){
      this.refs.zip_code.focus();
    }
  }

        <input
          onKeyPress={this.handleKeyPress}
          ref = 'name'
        />

        <input
          onKeyPress={this.handleKeyPressEmail}
          ref = 'email'
        />

        <input
          ref = 'zip_code'
        />
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止找到的最好的方法,但是我不希望每当我希望这种情况发生时创建一个函数来重复自己.是否有更好,更清洁的方式来实现这一点?

jzm*_*jzm 8

您可以通过for-in循环使用componentDidMount和auto bind refs.

http://codepen.io/jzmmm/pen/PzZgRX?editors=0010

  constructor() {
    super();
    this._handleKeyPress = this._handleKeyPress.bind(this);
  }

  // Loop through the ref's object, and bind each of them to onkeypress
  componentDidMount() {
    for (let x in this.refs) {
      this.refs[x].onkeypress = (e) => 
        this._handleKeyPress(e, this.refs[x]);
    }
  }

  // This checks ENTER key (13), then checks if next node is an INPUT
  // Then focuses next input box
  _handleKeyPress(e, field) {
    if (e.keyCode === 13) {
      e.preventDefault(); // Prevent form submission if button present
      let next = this.refs[field.name].nextSibling;

      if (next && next.tagName === "INPUT") {
        this.refs[field.name].nextSibling.focus();
      }
    }
  }

  render() {
    return (
        <form>
          <input type="text" name="name" ref='name' />
          <input type="text" name="email" ref='email' />
          <input type="text" name="zip_code" ref='zip_code' />
        </form>
    );
  }
Run Code Online (Sandbox Code Playgroud)


Vit*_*sov 8

如果输入量适中:

function handleEnter(event) {
  if (event.keyCode === 13) {
    const form = event.target.form;
    const index = Array.prototype.indexOf.call(form, event.target);
    form.elements[index + 1].focus();
    event.preventDefault();
  }
}
...
<form>
  <input onKeyDown={handleEnter} />
  <input onKeyDown={handleEnter} />
  <input />
</form>
Run Code Online (Sandbox Code Playgroud)

否则,您可以包装input到单独的组件中:

function MyInput(props) {
  return <input onKeyDown={handleEnter} {...props} />;
}
Run Code Online (Sandbox Code Playgroud)

密码笔


Gui*_*rmo 1

这就是我设法使其变得更简单的方法:

  @autobind
  handleKeyPress(value, event){
    if(event.key === 'Enter'){
      this.refs[event].focus();
    }
  }

    <input
      onKeyPress={(event) => this.handleKeyPress('email', event)}
      ref = 'name'
    />

    <input
      onKeyPress={(event) => this.handleKeyPress('zip_code', event)}
      ref = 'email'
    />

    <input
      ref = 'zip_code'
    />
Run Code Online (Sandbox Code Playgroud)