51 lines
1.1 KiB
React
51 lines
1.1 KiB
React
|
|
import { useEffect, useState } from "react";
|
|
import './Test.css'
|
|
|
|
|
|
export default function Test(){
|
|
const [hash, setHash] = useState(() => window.location.hash);
|
|
|
|
useEffect(() => {
|
|
const handleHashChange = () => {
|
|
setHash(window.location.hash);
|
|
};
|
|
|
|
window.addEventListener("hashchange", handleHashChange);
|
|
|
|
return () => {
|
|
window.removeEventListener("hashchange", handleHashChange);
|
|
};
|
|
}, []);
|
|
|
|
const showOptionPanel = hash === "#option";
|
|
|
|
function openOptionPanel() {
|
|
window.location.hash = "option";
|
|
}
|
|
|
|
function closeOptionPanel() {
|
|
// 去掉 #option,但不刷新页面
|
|
window.history.pushState(
|
|
"",
|
|
document.title,
|
|
window.location.pathname + window.location.search
|
|
);
|
|
|
|
// pushState 不会自动触发 hashchange,所以这里手动同步状态
|
|
setHash("");
|
|
}
|
|
|
|
return (
|
|
<div>
|
|
<button onClick={openOptionPanel}>打开设置面板</button>
|
|
|
|
{showOptionPanel && (
|
|
<div className="panel">
|
|
<h2>设置面板</h2>
|
|
<button onClick={closeOptionPanel}>关闭</button>
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
} |