Init Commit
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user