![](/img/trans.png)
[英]How to focus next input on pressing enter, in functional components? (TAB behavior)
[英]How to change focus to the next input if I am using components?
我需要通過按Enter鍵將焦點從第一個Input更改為第二個來模擬Tab按下。
如果我僅使用基本的相鄰輸入,則能夠實現此功能,但是使用組件時-我會失敗。 為了方便您,我在下面的代碼筆上有以下代碼:https: //codepen.io/irvingwash/pen/YoJpYx
class Input extends React.Component {
render() {
return (
<div className='Input'>
<input
type='text'
value={this.props.value}
onKeyPress={this.props.onKeyPress}
/>
</div>
);
}
}
class App extends React.Component {
mimickTabHandler = (event) => {
if (event.key === 'Enter') {
console.log('Pressed');
}
};
render() {
return (
<div className='App'>
Hello
<br />
<Input value='World' onKeyPress={this.mimickTabHandler} />
<br />
// This input must be focused
<Input value='Universe' />
</div>
)
}
}
您可以嘗試這樣。 盡管它不完整,因為一旦到達最后一個輸入,您仍然必須處理該做什么。 希望這可以幫助。
分叉的示例: https ://codepen.io/denz-io/pen/OeBWOe
因此,我們基本上只是遍歷所有輸入,假設您有5個輸入,請檢查event.target是否為循環中當前項的==並在其旁邊的輸入上執行.focus()。
mimickTabHandler = (event) => {
if (event.key === 'Enter') {
let inputsList = Object.values(document.getElementsByTagName("Input"))
inputsList.forEach((inp, key) => {
if (inp == event.target) {
inputsList[key + 1].focus();
}
})
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.