2016-10-03 63 views
2

我有多個輸入,並且我正在嘗試在下一個輸入達到最大長度時進行輸入焦點。
這裏是我的代碼:如何簡化這個反應組分?

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事件處理程序。

我該如何簡化這個問題,還是有更好的方法來實現我想要做的?

+3

如果一切正常,這可能是更適合的代碼審查姊妹網站 –

+0

@SamiKuhmonen嘿指點出來的感謝。我甚至不知道它存在。 – Dan

回答

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> 
    ) 
    } 
}); 
+0

嘿,謝謝,但我想我不應該使用[ref string](https://facebook.github.io/react/docs/more-about-refs.html#the-ref-string-attribute)。是否有可能與ref回調做到這一點? – Dan

+0

當然,請檢查此[jsBin](https://jsbin.com/xaqekujela/1/edit?html,js輸出)。 – dzv3

+0

再次感謝您! – Dan

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不是被立即設置。