基于路线的条件渲染

问题描述 投票:0回答:1

我有一个元素,仅当我在“ /”路线上时才显示,如果要更改,我想隐藏该元素我应该如何正确做?我正在使用react-router-dom来更改我使用的路由,所以我想这就是问题,我缺少什么?,我也尝试使用if(history.location =='/')then / else它不起作用

reactjs dom conditional-statements render router
1个回答
0
投票

您可以使用<Route />中的react-router-dom组件。

official react-router docs

Route组件可能是React Router中了解和学习使用的最重要组件。它的最基本职责是在其路径与当前URL匹配时呈现一些UI。

import React from "react";
import { render } from "react-dom";
import { BrowserRouter, Route } from "react-router-dom";

const MyComponent = () => (
  <Route path="/">
    <p>Only render when on "/" path.</p>
  </Route>
);

const App = () => (
  <BrowserRouter>
    <MyComponent />
  </BrowserRouter>
);

render(<App />, document.getElementById("root"));
© www.soinside.com 2019 - 2024. All rights reserved.