我正在尝试使用链接组件来启用我的应用程序的客户端呈现。以下是我的组件。
/**@jsx jsx */
import { css, jsx } from '@emotion/core';
import { fontFamily, fontSize, gray1, gray2, gray5 } from './../Styles';
import UserIcon from './UserIcon';
import { ChangeEvent } from 'react';
import { Link, BrowserRouter } from 'react-router-dom';
export const Header = () => {
const handleSearchInputChange = (e: ChangeEvent<HTMLInputElement>) => {
console.log(e.currentTarget.value);
};
return (
<div
css={css`
position: fixed;
box-sizing: border-box;
top: 0;
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px 20px;
background-color: #fff;
border-bottom: 1px solid ${gray5};
box-shadow: 0 3px 7px 0 rgba(110, 112, 114, 0.21);
`}
>
<Link
to="./"
css={css`
font-size: 24px;
font-weight: bold;
color: ${gray1};
text-decoration: none;
`}
>
Q & A
</Link>
<input
type="text"
placeholder="Search..."
css={css`
box-sizing: border-box;
font-family: ${fontFamily};
font-size: ${fontSize};
padding: 8px 10px;
border: 1px solid ${gray5};
border-radius: 3px;
color: ${gray2};
background-color: white;
width: 200px;
height: 30px;
:focus {
outline-color: ${gray5};
}
`}
onChange={handleSearchInputChange}
/>
<Link
to="./signin"
css={css`
font-family: ${fontFamily};
font-size: ${fontSize};
padding: 5px 10px;
background-color: transparent;
color: ${gray2};
text-decoration: none;
cursor: pointer;
span {
margin-left: 10px;
}
:focus {
outline-color: ${gray5};
}
`}
>
<UserIcon />
<span>Sign In</span>
</Link>
</div>
);
};
我在如下的App.tsx中使用BrowserRouter
const App = () => (
<div
className="App"
css={css`
font-family: ${fontFamily};
font-size: ${fontSize};
color: ${gray2};
`}
>
<Header />
<BrowserRouter>
<Switch>
<Redirect from="/home" to="/" />
<Route exact path="/" component={HomePage} />
<Route exact path="/search" component={SearchPage} />
<Route exact path="/ask" component={AskPage} />
<Route exact path="/signin" component={SignInPage} />
<Route component={NotFoundPage} />
</Switch>
</BrowserRouter>
</div>
);
export default App;
现在,当我运行我的应用程序时,我得到的错误为
Error: Invariant failed: You should not use <Link> outside a <Router>
▶ 25 stack frames were collapsed.
当我在链接组件的Header.tsx中使用BrowserRouter时,我的应用程序运行,但是当我单击链接时,仅URL发生更改,并且应用程序停留在主页上。不知道我在这里想念什么。
答案 0 :(得分:2)
使用Link
的Header组件被呈现在BrowserRouter组件之外,这就是它引发错误的原因。您可以将其呈现为BrowserRouter的子级,也可以呈现为默认路由,以使其接收路由器道具并能够正确使用Link
const App = () => (
<div
className="App"
css={css`
font-family: ${fontFamily};
font-size: ${fontSize};
color: ${gray2};
`}
>
<BrowserRouter>
<Route component={Header} />
<Switch>
<Redirect from="/home" to="/" />
<Route exact path="/" component={HomePage} />
<Route exact path="/search" component={SearchPage} />
<Route exact path="/ask" component={AskPage} />
<Route exact path="/signin" component={SignInPage} />
<Route component={NotFoundPage} />
</Switch>
</BrowserRouter>
</div>
);
export default App;