2017-07-07 43 views
2

我正在使用reactjs來嘗試和使用鍵盤類瀏覽組件列表,例如如何使用j和k鍵在Facebook上導航。當我第一次登陸頁面然後在使用j和k之後移動組件之間的焦點時,如何使用j鍵將焦點移動到列表中的第一個組件?導航組件列表

<ul className={s.feed}> 
    {this.props.data.map((item, index) => { 
    <li key={index} className={s.componentContainer}> 
     <Component component={item} /> 
    </li> 
    })} 
</ul> 

等什麼代碼的功能基本上是產生組件到有序列表和IM只是想知道我怎麼可以用J和K鍵在它們之間切換焦點,並沒有使用標籤。

+0

向我們顯示您的代碼。你在尋找[focus](https://stackoverflow.com/questions/17500704/javascript-set-focus-to-html-form-element)方法嗎? –

+0

我用代碼更新了它。我正在研究焦點方法,但我想知道是否有方法或其他方法將焦點移動到列表中的下一個項目? –

回答

2

目前我正在處理類似的問題。

假設你有這樣的狀態:

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> 
+0

最後五行中的for循環和setState方法應該做什麼? –

+0

那裏你更新 - 哪個項目具有'onFocuse'設置爲'true' – kurumkan

+0

我現在正在嘗試它,並且onFocus實際上並沒有關注組件,它只是一個真或假的值。我在哪裏可以實際關注組件? –