#javascript #reactjs
#javascript #reactjs
Вопрос:
У меня есть 4 входа, и я хочу, чтобы, когда пользователь заполнил первый ввод, он сосредоточился на втором вводе.
constructor(props) {
...
this.textInput1 = React.createRef();
this.textInput2 = React.createRef();
this.textInput3 = React.createRef();
this.textInput4 = React.createRef();
this.onChangeInputText = this.onChangeInputText.bind(this)
onChangeInputText(e){
const index = e.currentTarget.dataset.index;
console.log('index',index)
if(index == 1)
this.setState({'cardNumber1':e.target.value})
if(index == 2)
this.setState({'cardNumber2':e.target.value})
if(index == 3)
this.setState({'cardNumber3':e.target.value})
if(index == 4)
this.setState({'cardNumber4':e.target.value})
if (e.target.value.length == 4) {
this[`textInput${index 1}`].current.focus()
}
}
мое мнение:
<input onChange={this.onChangeInputText} data-index={4} ref={this.textInput4} value={cardNumber4} name="card4" type="text" class="form-control col-xs-3 col-sm-3" style={{paddingLeft:'0px !important;'}} required="" autocomplete="off" pattern="[0-9]*" tabindex="4" maxLength="4" />
<input onChange={this.onChangeInputText} data-index={3} ref={this.textInput3} value={cardNumber3} name="card3" type="text" class="form-control col-xs-3 col-sm-3" style={{paddingLeft:'0px !important;'}} required="" autocomplete="off" pattern="[0-9]*" tabindex="3" maxLength="4" />
<input onChange={this.onChangeInputText} data-index={2} ref={this.textInput2} value={cardNumber2} name="card2" type="text" class="form-control col-xs-3 col-sm-3" style={{paddingLeft:'0px !important;'}} required="" autocomplete="off" pattern="[0-9]*" tabindex="2" maxLength="4" />
<input onChange={this.onChangeInputText} data-index={1} ref={this.textInput1} value={cardNumber1} name="card1" type="text" class="form-control col-xs-3 col-sm-3" style={{paddingLeft:'0px !important;'}} required="" autocomplete="off" pattern="[0-9]*" tabindex="1" maxLength="4" />
но я получил это сообщение об ошибке:
Uncaught TypeError: Cannot read property 'current' of undefined
Я могу решить проблему с if
помощью инструкции:
if (e.target.value.length == 4) {
// this[`textInput${index 1}`].current.focus()
if(index == 1)
this.textInput2.current.focus();
if(index == 2)
this.textInput3.current.focus();
if(index == 3)
this.textInput4.current.focus();
}
Комментарии:
1. разве вы не забыли состояние в «if (e.target.value. длина == 4) { это. СОСТОЯНИЕ [
textInput${index 1}
].current.focus() }» ?2. Что
console.log('index',index)
регистрируется при сбое вашего кода?3. Я могу решить проблему с
if
помощью инструкции: ` если (например, target.value. длина == 4) { // this[textInput${index 1}
].current.focus() если (индекс == 1) this.textInput2.current.focus(); если (индекс == 2) this.textInput3.current.focus(); если (индекс == 3) это.textInput4.current.focus(); }`
Ответ №1:
if (e.target.value.length == 4) {
this[`textInput${index 1}`].current.focus()
}
итак, здесь this[`textInput${index 1}`]
это приводит к undefined в случае, если ваш индекс равен 4
и значение.длина также 4
таким образом, вы получаете this[textInpu5]
результат, который не определен
Или, если вы не проанализируете свой индекс, у number
вас будут такие условия, как this[textInput21]
или, которые также будут неопределенными
Ответ №2:
Если вы увеличите значение index
, то для четвертого элемента он будет пытаться получить доступ this.textInput5
, которого не существует — удалите 1
:
this[`textInput${index}`].current.focus();
Ответ №3:
index
оказывается строкой. Вы используете его как строку в своих if
сравнениях. Это работает, потому "1" == 1
что есть true
. Но когда вы пытаетесь выполнить математику, это фактически приводит к конкатенации строк. "1" 1
есть 11
.
Таким образом, строка, в которой возникает ошибка, вычисляется this.textInput11
как неопределенная.
Вы можете преобразовать index
в число в самом начале, чтобы избежать путаницы. Нравится const index = parseInt(e.currentTarget.dataset.index);