使用 React 和 J*aScript 实现跨类别预测列表的键盘导航

本文档旨在提供一个清晰的指南,讲解如何在 React 应用中,处理多类别预测列表,并允许用户通过键盘上下键进行导航选择。核心思路是将多类别数据扁平化,利用 `useState` 管理选中项的索引,并通过 props 将选中状态传递给子组件,实现高亮显示。同时,强调了避免使用数组索引作为唯一ID的重要性,并提供完整的代码示例,方便读者理解和应用。
在 React 应用中,实现跨类别预测列表的键盘导航,需要考虑数据的组织形式、状态的管理以及组件间的通信。 本教程将详细介绍如何使用 React 和 J*aScript 来实现这一功能,并提供完整的代码示例。
1. 数据结构设计
首先,需要设计合理的数据结构。避免直接使用数组索引作为唯一标识符(ID),因为这可能导致后续维护和调试的困难。推荐为每个预测项和类别都分配一个唯一的 id 属性。
const prediction = {
id: 1,
name: "Hello, world!"
};
const category = {
id: 1,
name: "First category",
predictions: [prediction]
};2. 组件化方案
将应用拆分为三个核心组件:
-
gories> : 负责渲染类别列表,并管理全局的选中状态。 -
: 负责渲染单个类别及其包含的预测项。 </strong>: 负责渲染单个预测项,并根据是否被选中应用高亮样式。</li></ul><h3>3. 数据扁平化</h3><p>为了方便键盘导航,将多层嵌套的类别和预测项数据扁平化为一个一维数组。可以使用 J*aScript 的 flatMap 方法来实现。</p><pre class="brus
h:php;toolbar:false;">const Categories = ({ categories }) => {
const allItems = categories.flatMap(x => x.predictions);
// ...
};4. 状态管理
使用 React 的 useState Hook 来管理当前选中项的索引 selectedIndex。
标贝AI虚拟主播
一站式虚拟主播视频生产和编辑平台
69
查看详情
const Categories = ({ categories }) => { const allItems = categories.flatMap(x => x.predictions); const [selectedIndex, setSelectedIndex] = React.useState(0); const selectedItem = allItems[selectedIndex]; // ... };selectedItem 存储了当前选中项的信息。
5. 组件间通信
将当前选中项的 id 通过 props 传递给子组件,以便它们能够判断自身是否被选中。
// <Categories> {categories.map(x => <Category key={x.id} ... selectedId={selectedItem.id} />)} // <pre class="brush:php;toolbar:false;"diction> const Prediction = ({ id, name, selectedId }) => { const isSelected = id === selectedId; return <li className={isSelected ? "highlight" : ""}>{name}</li>; };6. 键盘事件处理
在
组件上绑定 onKeyUp 事件,并根据按键类型更新 selectedIndex。需要进行边界检查,防止索引超出范围。 const Categories = ({ categories }) => { // ... const onKeyUp = (event) => { switch (event.code) { case "ArrowUp": setSelectedIndex(Math.max(0, selectedIndex - 1)); break; case "ArrowDown": setSelectedIndex( Math.min(allItems.length - 1, selectedIndex + 1) ); break; } }; return (<div onKeyUp={onKeyUp} tabIndex={-1}> ... </div>); };tabIndex="-1" 属性使得 div 元素可以接收键盘事件。
7. 完整示例代码
// Example data here. const teeShirts = [ { id: 1, name: "Black" }, { id: 2, name: "Red" }, { id: 3, name: "Blue" }, ]; const accessories = [ { id: 4, name: "Cool Cap" }, { id: 5, name: "Fancy Tie" }, { id: 6, name: "Medallion" }, ]; const countries = [ { id: 7, name: "United Kingdom" }, { id: 8, name: "United States" }, { id: 9, name: "Australia" }, ]; const categories = [ { id: 1, name: "T-Shirts", predictions: teeShirts }, { id: 2, name: "Accessories", predictions: accessories }, { id: 3, name: "Countries", predictions: countries }, ]; const Categories = ({ categories }) => { const allItems = categories.flatMap((x) => x.predictions); const [selectedIndex, setSelectedIndex] = React.useState(0); const selectedItem = allItems[selectedIndex]; const onKeyUp = (event) => { switch (event.code) { case "ArrowUp": setSelectedIndex(Math.max(0, selectedIndex - 1)); break; case "ArrowDown": setSelectedIndex( Math.min(allItems.length - 1, selectedIndex + 1) ); break; } }; return ( <div onKeyUp={onKeyUp} tabIndex={-1}> {categories.map((category) => ( <Category key={category.name} id={category.id} name={category.name} predictions={category.predictions} selectedId={selectedItem.id} /> ))} </div> ); }; const Category = ({ name, predictions, selectedId }) => { return ( <div> {name} <ul role="listbox"> {predictions.map((prediction) => ( <pre class="brush:php;toolbar:false;"diction key={prediction.name} id={prediction.id} name={prediction.name} selectedId={selectedId} /> ))} </ul> </div> ); }; const Prediction = ({ id, name, selectedId }) => { const isSelected = id === selectedId; return <li className={isSelected ? "highlight" : ""}>{name}</li>; }; // This is just bootstrapping so the example works const App = () => { return <Categories categories={categories} />; }; const root = ReactDOM.createRoot(document.getElementById("root")); root.render( <React.StrictMode> <App /> </React.StrictMode> );.highlight { color: red; font-weight: bold; }<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script> <div id="root"></div>
总结
通过以上步骤,可以实现一个支持键盘导航的跨类别预测列表。关键在于数据的扁平化、状态的管理以及组件间的通信。同时,需要注意避免使用数组索引作为唯一标识符,并进行边界检查,确保应用的稳定性和可靠性。 这个方法可以应用到各种需要键盘交互的列表型组件中,提高用户体验。
以上就是使用 React 和 J*aScript 实现跨类别预测列表的键盘导航的详细内容,更多请关注其它相关文章!

h:php;toolbar:false;">const Categories = ({ categories }) => {
const allItems = categories.flatMap(x => x.predictions);
// ...
};