ReactJS:处理空间导航(键盘和游戏手柄)

ReactJS: Handle Spatial Navigation (Keyboard and Gamepad)

我正在 ReactJS 中创建这个类似 netflix 的应用程序,我需要实现空间控制:您应该能够使用键盘箭头键(而不是选项卡)或游戏手柄通过一次聚焦一个元素来导航应用程序。

此应用程序可能会 运行 在包括电视和平板电脑在内的任何设备上的网络视图中,因此无论我想使用哪种浏览器原生解决方案,我都需要确定它是否得到普遍支持。

是否有 reactjs 库或 HTML5 Api 使用游戏手柄和键盘箭头键提供跨浏览空间导航?

您可以 Mousetrap.js 使用箭头键绑定和取消绑定您需要使用生命周期挂钩 componentDidMountcomponentWillUnmount.

执行的任何操作
 componentDidMount() {
        Mousetrap.bind(theArrowKeyToBind, () => theActionToPerform);
    }
    componentWillUnmount() {
        Mousetrap.unbind(theArrowKeyToBind, () => theActionToPerform);
    }

看看https://github.com/dead/react-js-spatial-navigation 它是 js-spatial-navigation 的包装器。我在测试电视应用程序中使用了它,效果很好!它仍然缺少示例和文档,但它非常简单。

<SpatialNavigation>
 // your components here
 // for a focusable content you can just wrapper it around the
 <Focusable onFocus={event => this.onFocusFunction(event)} onUnfocus={event => this.onUnfocusFunction(event)}>
     // Your focusable content here
 </Focusable>
 // more components
</SpatialNagivation>

好吧,除了 angularJS 或 ReactJS 库之外,您应该在您的应用程序中寻找抽象的东西来进行空间导航。只需浏览下面的库并查看 GitHub 中给定的示例。 NaviboardJS

在项目中 use.Include 导航板很简单,并且可以 class 导航到所需的元素,并将其包含在具有某些 ID 的其他元素中。即 ParentElementID。检查以下内容,例如

<div class="wrapper" id='ParentElementID'>
  <div class="box navigable">A</div>
  <div class="box navigable">B</div>
  <div class="box navigable">C</div>
  <div class="box navigable">D</div>
  <div class="box navigable">E</div>
</div>

之后从您的脚本中调用 API :

naviBoard.setNavigation('ParentElementID')

该视图将可以导航,并且可以通过键盘箭头键进行访问。

库提供了其他有前途的 API 以及其他用例。

查看示例 link:

https://jsfiddle.net/amanboss9/zv5hocxq/2/embedded/result