这些是我的输入内容
<input onChange={(event)=>this.setState({cardNumber4:event.target.value})} name="card4" type="text" class="form-control col-xs-3 col-sm-3" style={{paddingLeft:'0px !important;'}} required="" autocomplete="off" tabindex="4" maxlength="4" />
<input onChange={(event)=>this.setState({cardNumber3:event.target.value})} name="card3" type="text" class="form-control col-xs-3 col-sm-3" style={{paddingLeft:'0px !important;'}} required="" autocomplete="off" tabindex="3" maxlength="4" />
<input onChange={(event)=>this.setState({cardNumber2:event.target.value})} name="card2" type="text" class="form-control col-xs-3 col-sm-3" style={{paddingLeft:'0px !important;'}} required="" autocomplete="off" tabindex="2" maxlength="4" />
<input onChange={(event)=>this.setState({cardNumber1:event.target.value})} name="card1" type="text" class="form-control col-xs-3 col-sm-3" style={{paddingLeft:'0px !important;'}} required="" autocomplete="off" tabindex="1" maxlength="4" />
现在我想在填写完第一个输入后转到下一个输入(我不想使用制表符或下一个键)。我该怎么办?
答案 0 :(得分:0)
在这种情况下,您应该使用refs。 来自react docs的示例:
class CustomTextInput extends React.Component {
constructor(props) { super(props); // create a ref to store the textInput DOM element
this.textInput = React.createRef();
this.focusTextInput = this.focusTextInput.bind(this);
}
focusTextInput() {
// Explicitly focus the text input using the raw DOM API
// Note: we're accessing "current" to get the DOM node
this.textInput.current.focus();
}
render() {
// tell React that we want to associate the <input> ref
// with the `textInput` that we created in the constructor
return ( <div>
<input type="text" ref={this.textInput} />
<input type="button" value="Focus the text input" onClick={this.focusTextInput} />
</div> );
}
}
答案 1 :(得分:0)
您可以通过使用反应引用和输入中的数据属性以编程方式集中输入。这是一个粗糙的示例,请根据您的需要进行更改:
handleInputChange(e) {
const index = e.currentTarget.dataset.index;
if (e.target.value.length > 4) {
this[`textInput${index + 1}`].current.focus()
}
}
...
...
...
<input onChange={this.handleInputChange} data-index={1} ref={this.textInput1} name="card1" type="text" tabindex="4" maxlength="4" />
<input onChange={this.handleInputChange} data-index={2} ref={this.textInput2} name="card1" type="text" tabindex="4" maxlength="4" />
您可以通过在构造函数上使用React.createRef()
来创建引用。示例:
this.textInput1 = React.createRef();
this.textInput2 = React.createRef();