【发布时间】:2021-11-03 14:41:27
【问题描述】:
正如标题所说,我实际上是在尝试通过使用循环列表中的左右箭头键来导航我的网页。每次按下右箭头,导航栏选择右边的下一个元素,每次按下左箭头,它选择左边的页面。
我已经创建了一个函数来检测左右箭头按键,但到目前为止它只是console.logs,我对路由器和开关不是很熟悉,所以我试图开发一些函数来改变操纵导航栏使用箭头键(同时保持选择能力)
import "./App.css";
import { useRef } from "react";
import { useEffect } from "react";
import Navigation from "./Components/UI/Navigation";
import CentralReport from "./Components/Central Report/CentralReport";
import ImageSlideShow from "./Components/Slideshow/ImageSlideShow";
import MapSlideShow from "./Components/Slideshow/MapSlideShow";
import { BrowserRouter as Switch, Route } from "react-router-dom";
function useKey(key, cb) {
const callbackRef = useRef(cb);
useEffect(() => {
callbackRef.current = cb;
});
useEffect(() => {
function handle(event) {
if (event.code === key) {
callbackRef.current(event);
}
}
document.addEventListener("keydown", handle);
return () => document.removeEventListener("keydown", handle);
}, [key]);
}
function App() {
function handleArrowLeft() {
console.log("Left");
}
function handleArrowRight() {
console.log("Right");
}
useKey("ArrowLeft", handleArrowLeft);
useKey("ArrowRight", handleArrowRight);
return (
<div>
<Switch>
<Route exact path="/central-report" component={CentralReport} />
<Route path="/images" component={ImageSlideShow} />
<Route path="/maps" component={MapSlideShow} />
</Switch>
{/* NavBar */}
<Navigation />
</div>
);
}
export default App;
【问题讨论】:
标签: javascript reactjs react-redux react-hooks