React router dom:如何更新包装器组件上的道具



我的应用程序组件如下:

const App = (props) => (
<BrowserRouter>
<PageTheme {...some props I'd like to change on route change}>
<Switch>
<Route exact path="/example">
<Example {...props} />
</Route>
<Route exact path="/example/detail/:exampleId">
<ExampleDetail {...props} />
</Route>
</Switch>
</PageTheme>
</BrowserRouter>
);

包装SwitchPageTheme组件有一些导航UI,以及一些关于页面背景颜色的选项等。有没有办法为PageTheme提供每个路线的一些特定道具?还是在每个Route中放入一个新的PageTheme组件是最好的选择?谢谢

您可以使用withRouter并用它包装PageTheme

export default withRouter(PageTheme);

如果PageTheme是功能组件,则使用useLocation钩子。然后,您将可以访问location,并根据当前路线/url施展魔法。

相关内容

最新更新