reactjs 在启动时预先选择路线按钮[重复]

ffx8fchx  于 2023-06-29  发布在  React
关注(0)|答案(1)|浏览(96)

此问题已在此处有答案

is there a way to set a default route with React-Router v6(5个答案)
2天前关闭。
我有一个路由器页面,它有2个按钮,每个按钮都调用相应的js函数来呈现文本。当启动页面时,用户必须单击任一按钮以调用函数。按钮是“短”和“长”。我想“短”默认情况下启用,但用户应该仍然能够在“长”和“短”之间切换。

import {Link, resolvePath, useMatch, useResolvedPath} from "react-router-dom"

export default function Selector() {
    return (
        <div className="bar">
            <ul>
                <CustomLink to="/short">Short</CustomLink>
                <CustomLink to="/long">Long</CustomLink>
            </ul>
        </div>
    )
}

function CustomLink({to, children, ...props}) {
    const resolvedPath = useResolvedPath(to)
    const isActive = useMatch({ path: resolvedPath.pathname, end: true})
    return (
        <li className={isActive ? "active" : ""}>
            <Link to={to} {...props}>
                {children}</Link>
        </li>
    )
}

        {/* Displaying the result*/}
        <div className="container1">
          <Selector/>
            <Routes>
              <Route path="/short" element = {<Short/>}/>
              <Route path="/long" element = {<Long/>}/>
            </Routes>
        </div>

到目前为止,无论我尝试了什么,都将页面锁定在“短”上,不允许用户切换到“长”。

j13ufse2

j13ufse21#

import {Route, Routes, Navigate} from "react-router-dom"

            <Route index element={<Navigate to="/short"/>} />

相关问题