[英]React-router: How to resize header after navigating to new page?
我有一个 react-router 应用程序,它带有一个 header 组件,在“/home”路径下占据页面的整个高度。 当我导航到新路径“/foo”时,我需要更改标题的高度。
当我通过在浏览器中输入 url 直接加载任一页面时,它具有正确的高度:
但是,当我使用以下代码从 /home 导航到 /foo 时,URL 会正确更改,但 DOM 不会重新渲染。 header 的高度仍然为 100vh,并且 DOM 不包含 Foo 组件。
应用程序.js
const App = () => {
return (
<Provider store={store}>
<Router>
<Header />
<Switch>
<Route path='/home' component={null}/>
<Route path='/foo' component={Foo}/>
</Switch>
</Router>
</Provider>
);
}
主页.js
const Home = () => {
// ... some more code
const navigate = useCallback(to => {
history.push(to);
}, []);
// ... some more code
};
Header.js
const Header = () => {
const { pathname } = useLocation();
const style = pathname === '/home'
? { height: '100vh'}
: { height: '15vh'}
return (
<div style={style}>
{ /* ...some more code */ }
</div>
);
};
Foo.js
const Foo = () => {
return (
<div>
Foo...
</div>
);
};
我怀疑问题是在更改路径时不会触发重绘。
我建议在 header 中使用 React-Routers 'Route' 组件(假设额外的 div 不是问题)。
所以它看起来像这样:
const HeaderInternal = () => {
return { /* ... some header code */ }
}
const Header = () => {
return (
<>
<Route path='/home'><div style={{ height: '100vh'}}><HeaderInternal /> </div></Route>
<Route path='/foo'><div style={{ height: '15vh'}}><HeaderInternal /> </div></Route>
</>
);
};
我没有直接测试过这个,但是当你切换页面时,Route 组件应该强制重绘。 HeaderInternal 只是为了 DRY,但如果你有一个组件,你可以跳过它。
header 不会重新渲染,因为它位于 Switch 外部。 因此,更改路线不会重新触发 header。 您必须在 Home 和 Foo 组件中导入 header 以便它在更改路径时重新渲染。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.