如何简化此反应组件?

时间:2016-10-03 07:15:41

标签: reactjs

我有多个输入,一旦达到最大长度,我试图将输入焦点放在下一个输入上 这是我的代码:

handleTextChange1(e) {
    const { value, maxLength } = e.target;
    if (value.length === maxLength) {
       ReactDOM.findDOMNode(this.nextComponent1).focus();
    }
}
handleTextChange2(e) {
    const { value, maxLength } = e.target;
    if (value.length === maxLength) {
       ReactDOM.findDOMNode(this.nextComponent2).focus();
    }
}
render() {
    return (
       <form onSubmit={this.handleSubmit.bind(this)}>
          <input onChange={this.handleTextChange1.bind(this)} maxLength="4"/>
          <input ref={c => this.nextComponent1=c} onChange={this.handleTextChange2.bind(this)} maxLength="4" />
          <input ref={c => this.nextComponent2=c}  maxLength="4"/>
       </form>
    )
}

我不希望每个输入都有不同的onChange事件处理程序。

我如何简化这个或者是否有更好的方法来实现我想要做的事情?

2 个答案:

答案 0 :(得分:1)

快速简化并使其成为DRYer,您可以将下一个组件作为参数聚焦到onChange处理程序。

https://jsbin.com/cakujozoga/edit?html,js,output

var App = React.createClass({
  handleSubmit: function() {},

  handleTextChange: function(nextComponent, e) {
    const { value, maxLength } = e.target;
    if (value.length === maxLength) {
       ReactDOM.findDOMNode(this.refs[nextComponent]).focus();
    }
  },

  render: function() {
    return (
       <form onSubmit={this.handleSubmit.bind(this)}>
          <input onChange={this.handleTextChange.bind(this, "nextComponent1")} maxLength="4"/>
          <input ref="nextComponent1" onChange={this.handleTextChange.bind(this, "nextComponent2")} maxLength="4" />
          <input ref="nextComponent2" maxLength="4"/>
       </form>
    )
  }
});

答案 1 :(得分:0)

概括您的事件处理程序:

focusWhenChangeHappened(component) {
  return function eventHandler(e) {
    const { value, maxLength } = e.target;
    if (value.length === maxLength) {
       ReactDOM.findDOMNode(component).focus();
    }
  }
}

附加实际的事件处理程序

... onChange={this.focusWhenChangeHappened(this.component1)} ...
... onChange={this.focusWhenChangeHappened(this.component2)} ...

您可能需要解决ref未立即设置的问题。