不太熟悉react路由器,但我需要NavLink的功能来设置父li元素的活动类,而不是a元素.
为了实现这一点,我只看了它的源代码NavLink并将其复制到一个新元素.(使用打字稿的示例,但与js大致相同)
import * as React from 'react';
import { Link, withRouter, Route } from 'react-router-dom';
class LiNavLink extends React.Component<any, {}> {
render() {
const {to,exact, strict, activeClassName, className, activeStyle, style, isActive: getIsActive, ...rest } = this.props;
return (
<Route
path={typeof to === 'object' ? to.pathname : to}
exact={exact}
strict={strict}
children={({ location, match }) => {
const isActive = !!(getIsActive ? getIsActive(match, location) : match)
return (
<li
className={isActive ? [activeClassName, className].join(' ') : …Run Code Online (Sandbox Code Playgroud) 关于未解决的问题(作为最终结论)
我也遇到了同样的问题.
https://reacttraining.com/react-router/web/guides/quick-start promotereact-router-dom
此外,人们list down routes在一个文件而不是内部组件中找到更好的结果.
引用的内容: https ://github.com/ReactTraining/react-router/tree/master/packages/react-router-config
工作的东西(大多数):
import * as React from 'react'
import {BrowserRouter as Router, Route, Switch } from 'react-router-dom'
export const Routes = () => (
<Router>
<div>
<Switch>
<Route exact path="/login" component={Login}/>
<MainApp path="/">
<Route path="/list" component={List}/>
<Route path="/settings" component={Settings}/>
</MainApp>
<Route path="*" component={PageNotFound}/>
</Switch>
</div>
</Router>
)
Run Code Online (Sandbox Code Playgroud)
有些东西不起作用:
site.com/SomeGarbagePath 显示<MainApp>我认为.
<Route path="*" component={PageNotFound}/>
更新
/ - Home - parent of …Run Code Online (Sandbox Code Playgroud) 我使用react-router-dom在我的主React组件中得到了相当多的TypeScritp错误.所有子组件都返回错误:
error TS2322: Type 'typeof NotFound' is not assignable to type 'StatelessComponent<void | RouteComponentProps<any>> | ComponentClass<void | RouteComponentProps<a...'.
Type 'typeof NotFound' is not assignable to type 'ComponentClass<void | RouteComponentProps<any>>'.
Types of parameters 'props' and 'props' are incompatible.
Type 'void | RouteComponentProps<any> | undefined' is not assignable to type '{} | undefined'.
Type 'void' is not assignable to type '{} | undefined'.
error TS2322: Type 'typeof Index' is not assignable to type 'StatelessComponent<void | RouteComponentProps<any>> | ComponentClass<void | RouteComponentProps<a...'.
Type 'typeof …Run Code Online (Sandbox Code Playgroud) 我正在尝试为我的React应用程序使用路由器.我尝试了一段时间以来一直在使用的东西,但似乎无法实现.已hashHistory在React Router v4中删除/重新格式化?
<Router history={hashHistory}>
<Route path='/' component={MainContainer} />
</Router>
Run Code Online (Sandbox Code Playgroud) 我正在开发一个单页的ReactJS Web应用程序,但我知道在定义路由时我做错了React Router V4.
我的问题如下:PrivateRoute在我的routes.js文件中没有按预期工作.也就是说,我不知道为什么,但我的侧边栏菜单,我的主要的子组件App,不能正常工作:当我点击我的PrivateRoute组件的菜单项(在这种情况下,Page1)有一些错误.当我说错误时,我的意思是当我点击a的菜单项时PrivateRoute,侧边栏菜单配置错误.将Page1呈现component()的内容,但侧边栏菜单中的菜单项不会保持高亮显示:在这种情况下,它会重定向到列表中的第一个菜单项MainHome.
尽管如此,如果我改变我的标记Page1部分从PrivateRoute到ConfigRoute我的routes.js文件,一切工作正常.
从我的文件样本index.js(主)routes.js,App.js以及side-menu.js:
index.js (主要)档案:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import Routes from './routes';
import store from './store';
ReactDOM.render(
<Provider store={store}>
<Routes/>
</Provider>,
document.getElementById('root')
);
Run Code Online (Sandbox Code Playgroud)
routes.js 文件:
import React, { Fragment } from …Run Code Online (Sandbox Code Playgroud) 我试图了解(v5)包和之间的区别,BrowserRouter以及Router对react-router-dom下面的示例有什么区别。
该文件说:
BrowserRouter A,使用HTML5历史记录API(pushState,replaceState和popstate事件)使UI与URL保持同步。
来源:https : //reacttraining.com/react-router/web/api/BrowserRouter
路由器 所有路由器组件的通用底层接口。通常,应用将使用高级路由器之一代替:BrowserRouter,HashRouter,MemoryRouter,NativeRouter,StaticRouter
来源:https : //reacttraining.com/react-router/web/api/Router
据我了解,我应该为HTML5浏览器应用程序使用BrowserRouter,到目前为止,我一直在这样做。
history.push(...)示例:
我正在尝试history.push('/myNewRoute')在一个大块内执行一个:
import history as './history';
...
export function someAsyncAction(input) {
return dispatch => {
fetch(`${API_URL}/someUrl`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ input }),
}).then(() => {
history.push('/myNewRoute');
}).catch((err) => {
dispatch(setError(err));
})
};
};
Run Code Online (Sandbox Code Playgroud)
history 定义为此模块:
import { createBrowserHistory } from 'history';
export default createBrowserHistory();
Run Code Online (Sandbox Code Playgroud)
并且history还将传递到我的路由器: …
html5-history reactjs react-router react-thunk react-router-dom
我目前正在构建一个模式库,其中已Button使用React和构建了一个组件styled-components。基于该Button组件,我希望所有Links组件看起来完全相同,并接收完全相同的道具。为此,我使用as来自中的prop styled-components,它使我可以将已构建的元素用作另一个标签或组件。
按钮组件
import * as React from 'react'
import { ButtonBorderAnimation } from './ButtonAnimation'
import { ButtonProps, ButtonVariant } from './Button.types'
import { ButtonBase, LeftIcon, RightIcon } from './Button.styled'
function Button({
variant = ButtonVariant.Filled,
children,
leftIcon = null,
rightIcon = null,
...props
}: ButtonProps): JSX.Element {
return (
<ButtonBase variant={variant} {...props}>
{variant !== ButtonVariant.Ghost ? (
<ButtonBorderAnimation {...props} />
) : null}
{leftIcon ? <LeftIcon>{leftIcon}</LeftIcon> : …Run Code Online (Sandbox Code Playgroud) javascript typescript reactjs styled-components react-router-dom
当我尝试从 react-router-dom 模块导入 useRouteMatch 时出现此错误,出现此错误:
尝试导入错误:“useRouteMatch”未从“react-router-dom”导出。
我有错误版本的 react-router-dom 模块吗?
import {
BrowserRouter as Router,
Switch,
Route,
Link,
useRouteMatch,
useParams
} from "react-router-dom";Run Code Online (Sandbox Code Playgroud)
我查看了模块的导出,实际上并没有导出。我有错误的版本吗?
import _BrowserRouter from "./BrowserRouter";
export { _BrowserRouter as BrowserRouter };
import _HashRouter from "./HashRouter";
export { _HashRouter as HashRouter };
import _Link from "./Link";
export { _Link as Link };
import _MemoryRouter from "./MemoryRouter";
export { _MemoryRouter as MemoryRouter };
import _NavLink from "./NavLink";
export { _NavLink as NavLink };
import _Prompt from "./Prompt";
export { _Prompt …Run Code Online (Sandbox Code Playgroud)我正在开发一个使用引人注目的Dash 模板的项目。在这里,我在从 URL 更改路由时遇到一些路由问题。
auth.js
import React, { lazy, Suspense } from "react"
import { Spin } from "antd"
import { Switch, Route, Redirect } from "react-router-dom"
import AuthLayout from "../container/profile/authentication/Index"
const Login = lazy(() =>
import("../container/profile/authentication/overview/SignIn")
)
const SignUp = lazy(() =>
import("../container/profile/authentication/overview/SignUp")
)
const ForgetPassword = lazy(() =>
import("../container/profile/authentication/overview/ForgetPassword")
)
const EmailConfirmation = lazy(() =>
import("../container/profile/authentication/overview/EmailConfirmation")
)
const VerificationPage = lazy(() =>
import("../container/profile/authentication/overview/VerificationPage")
)
const NotFound = () => {
console.log("NOT FOUND")
return <Redirect to="/" />
}
const …Run Code Online (Sandbox Code Playgroud) javascript reactjs react-router react-router-dom react-hooks
我目前正在将使用creat-react-app创建的项目迁移到next.js项目。
我面临的一件事是将matchPath函数从react-router-dom迁移到某种next.js函数,比较当前路径名和一种传递的href路由名称,以便实现并选择当前导航项。
import { useLocation, matchPath } from 'react-router-dom';
const NavBar = ({ item, pathname }) => {
const open = matchPath(pathname, {
path: item.href,
exact: false
});
...
}
Run Code Online (Sandbox Code Playgroud)
我能够pathname使用next/router获取当前电流,但之后,我不知道如何比较它们。
import { useRouter } from 'next/router';
const NavBar = () => {
const { pathname } = useRouter();
...
}
Run Code Online (Sandbox Code Playgroud)
这种情况下,该如何解决呢?
提前致谢。
react-router-dom ×10
reactjs ×10
react-router ×5
javascript ×2
typescript ×2
next.js ×1
react-hooks ×1
react-thunk ×1