目前我正在處理類似的問題。
假設你有這樣的狀態:
items = [
{
name: 'a',
onFocus: true
},
{
name: 'b',
onFocus: false
}
];
在你lifecicle方法添加和刪除enent聽衆
componentWillMount() {
document.addEventListener("keydown", this.handleKeyDown, false);
}
componentWillUnmount() {
document.removeEventListener("keydown", this.handleKeyDown);
}
這裏是handleKeyDown - 你只是在處理程序中設置的onfocus值:
handleKeyDown(e) {
let index = -1;
const items = this.state.items;
items.map((item, i) =>{
if(item.onFocus)index = i;
});
switch(e.keyCode) {
case 74:
e.preventDefault();
if(index > 0) i--;
break;
case 75:
e.preventDefault();
if(index < this.state.items.length - 1) i++;
break;
}
for(let i = 0; i < items.length; i++) {
items[i].onFocus = i === index;
}
this.setState({items});
}
並取決於哪個元素onFocus
設置爲true - 您可以設置(例如)適當的類別:
<ul>
{this.props.data.map((item, i) => {
<li key={i}>
<Component component={item} className={item.onFocus ? 'active' : ''} />
</li>
})}
</ul>
向我們顯示您的代碼。你在尋找[focus](https://stackoverflow.com/questions/17500704/javascript-set-focus-to-html-form-element)方法嗎? –
我用代碼更新了它。我正在研究焦點方法,但我想知道是否有方法或其他方法將焦點移動到列表中的下一個項目? –