Lin*_*s J 13 express reactjs next.js
因此,我正在开发一个 nodejs 应用程序,我将在该应用程序上运行我的新网站,并且我想为客户端的用户提供一种方式来显示不同的内容,并根据用户按下的内容重新呈现。我的想法是,例如,首先用户会看到“请先选择一个工具”,然后用户将在导航栏中选择一个工具,然后页面将重新呈现并显示在大屏幕中选择的工具,网址为例如然后更改 /admin/[ToolSelected]。
唯一的事情是我不知道如何实现这一目标。我在想,客户端代码可以检测到 url 是什么,并将其作为页面变量放置,然后该工具将根据页面变量的内容显示一个 IF 语句。
我的理论是否可行,或者如何以有效的方式实现这一目标?
这是我的主页代码:
// Including Navbar and css
import AdminLayout from '../comps/admin/adminLayout'
// the so called "tools" more will exist in the future
import Passform from '../comps/admin/tools/passform'
// Fetching the current url the user is on
var page = CURRENT_URL;
const jumbotron = {
background: 'white'
}
const Admin = (page) => (
<AdminLayout>
<style global jsx>
{
`body {
background: #eff0f3;
}`
}
</style>
<div className="jumbotron" style={jumbotron}>
{(page == "passform") ? (
<Passform/>
) : (
<h3>Something is wrong :/ . {page}</h3>
)}
</div>
</AdminLayout>
)
export default Admin
Run Code Online (Sandbox Code Playgroud)
fel*_*osh 12
您可以使用withRouterHOC包装您的组件,这将注入router具有当前pathname.
import { withRouter } from 'next/router';
const Admin = ({ router }) => (
<AdminLayout>
<style global jsx>
{`
body {
background: #eff0f3;
}
`}
</style>
<div className="jumbotron" style={jumbotron}>
{router.pathname == 'passform' ? <Passform /> : <h3>Something is wrong :/ . {page}</h3>}
</div>
</AdminLayout>
);
export default withRouter(Admin);
Run Code Online (Sandbox Code Playgroud)
编辑
如果你更喜欢钩子,你可以使用useRouter钩子。
import { useRouter } from 'next/router';
const Admin = () => {
const router = useRouter();
return (
<AdminLayout>
<style global jsx>
{`
body {
background: #eff0f3;
}
`}
</style>
<div className="jumbotron" style={jumbotron}>
{router.pathname == 'passform' ? <Passform /> : <h3>Something is wrong :/ . {page}</h3>}
</div>
</AdminLayout>);
}
;
export default Admin;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14161 次 |
| 最近记录: |