简体   繁体   English

如何使用 React Router 链接到由另一个路由渲染的组件内的路由

[英]How to link to Routes inside the component rendered by another Route with React Router

i'm trying to use react router in my reactjs app.我正在尝试在我的 reactjs 应用程序中使用 react 路由器。 And I encountered this problem:我遇到了这个问题:

This is what i'm trying to do:这就是我想要做的:

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

import About from '../Pages/About';
import Home from '../Pages/Home';
import Topics from '../Pages/Topics';
import LinkTest from '../Pages/LinkTest';

class AppRouter extends Component {
  render() {
    return (
        <Router>
          <div>
            <ul>
              <li>
                <Link to="/home">Home</Link>
              </li>
              <li>
                <Link to="/about">About</Link>
              </li>
              <li>
                <Link to="/topics">Topics</Link>
              </li>
              <Route path="/home" component={LinkTest}/>
            </ul>

            <hr />

            <Route path="/home" component={Home}/>
            <Route path="/about" component={About} />
            <Route path="/topics" component={Topics} />

          </div>
      </Router>
    );
  }
}

export default AppRouter;

Ignore "about" and "topic" component, when I click on "Home" link, it should target 2 routes, one will render "LinkTest" and the other renders "Home".忽略“about”和“topic”组件,当我点击“Home”链接时,它应该针对2条路由,一个渲染“LinkTest”,另一个渲染“Home”。

This is what inside "LinkTest":这是“LinkTest”内部的内容:

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

class LinkTest extends Component {
  render() {
      const {match}=this.props;
    return (
        <div>
            <Link to={`${match.url}/Test`}>Link To Test</Link>
        </div>
    );
  }
}

export default LinkTest;

And inside my "Home" component:在我的“主页”组件中:

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

import Test from './Test';

class Home extends Component {
  render() {
      const {match} = this.props;
      console.log(match.url);
    return (
        <Router>
            <div>
                <h2>
                    Hello from Home page
                    <Link to={`${match.url}/Test`}>Link To Test</Link>
                    <Route path={`${match.url}/Test`} component={Test}/>
                </h2>

            </div>
        </Router>

    );
  }
}

export default Home;

However:然而:

  • When i click on the link inside "LinkTest" component (which was rendered earlier), the url on the browser is shown " http://localhost:3000/home/Test ", but nothing happens.当我单击“LinkTest”组件(之前呈现的)内的链接时,浏览器上的 url 显示为“ http://localhost:3000/home/Test ”,但没有任何反应。

  • When i clicked on the link inside "Home" component, (which was rendered the same time as the "LinkTest" using the same link), it showed the same url on the browser: " http://localhost:3000/home/Test ", only this time it rendered the "Test" component.当我单击“Home”组件中的链接时(使用相同链接与“LinkTest”同时呈现),它在浏览器上显示相同的 URL:“ http://localhost:3000/home/测试”,只是这次它呈现了“测试”组件。

Why does this happen?为什么会发生这种情况? (what i want to achieve is I want to use the link inside "LinkTest" to render "Test" component inside "Home" component, or something similar). (我想要实现的是我想使用“LinkTest”中的链接来呈现“Home”组件中的“Test”组件,或类似的东西)。

I hope this is clear enough.我希望这已经足够清楚了。

You can do it in following way:您可以通过以下方式进行:

<Route exact path='/a' component={A} />
<Route path='/b' component={B} />

// Following should be router inside Component B
<Route exact path='/b/abc' component={OtherComponent}

If you want I've prepared few react-router 4 examples.如果您愿意,我已经准备了一些 react-router 4 示例。 These are hosted here.这些都托管在这里。 https://github.com/SandipNirmal/react-router-examples https://github.com/SandipNirmal/react-router-examples

If you need Nested routing inside ComponentB you should add Link s for those Route s as well.如果您需要在ComponentB嵌套路由,您还应该为这些Route添加Link And use match.url and match.path to build the nested Link s and Route s.并使用match.urlmatch.path构建嵌套的LinkRoute

const ComponentB = ({ match }) => {
    return (
        <div> 
            <div>
                <ul>
                    <li><Link to={`${match.url}/c`}>Component C</Link></li>

                    // more Links
                    <li><Link to={`${match.url}/css`}>CSS</Link></li>
                    <li><Link to={`${match.url}/react`}>React</Link></li>
                </ul>
            </div>
            <div>
                <Route path={`${match.path}/c`} component={ComponentC} />

                // more nested Routes
                <Route path={`${match.path}/css`} render={() => { return <h1>CSS</h1> }}/>
                <Route path={`${match.path}/react`} render={() => { return <h1>React</h1> }}/>
            </div>
        </div>
    );
}

Nested routing嵌套路由

Components created via Route will automatically be passed the following prop objects: match , location and history .通过Route创建的组件将自动传递以下prop对象: matchlocationhistory

Using match you can implement nested Route s.使用match您可以实现嵌套的Route s。 The match object contains the following properties: match对象包含以下属性:

  • params — (object) Key/value pairs parsed from the URL corresponding to the dynamic segments of the path params — (对象)从对应于路径动态段的 URL 解析的键/值对
  • isExact — (boolean) true if the entire URL was matched (no trailing characters) isExact — (boolean) true 如果整个 URL 匹配(没有尾随字符)
  • path(string) The path pattern used to match. path —— (字符串)用于匹配的路径模式。 Useful for building nested Route s用于构建嵌套的Route s
  • url(string) The matched portion of the URL. url(字符串)URL 的匹配部分。 Useful for building nested Link s用于构建嵌套的Link s

Reference参考

  1. https://medium.freecodecamp.org/beginners-guide-to-react-router-4-8959ceb3ad58 https://medium.freecodecamp.org/beginners-guide-to-react-router-4-8959ceb3ad58
  2. https://medium.com/@pshrmn/a-simple-react-router-v4-tutorial-7f23ff27adf https://medium.com/@pshrmn/a-simple-react-router-v4-tutorial-7f23ff27adf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何 1). 放一个 div,2)。 渲染一个内部没有路由的组件<routes>在 v6 React 中使用 React Router?</routes> - How to 1). put a div , 2). render a component without Route inside <Routes> with React Router in v6 React? 如何使用反应路由器中的链接组件访问嵌套路由中的先前索引路由? - How to access previous index route in nested routes using Link component from react router? 如何更新正在“react-router-dom”路由上呈现的组件? - How to update component that is being rendered on route of 'react-router-dom'? React Router:在呈现的Route组件中访问历史记录 - React Router: access history in rendered Route component 使用反应路由器路由到不同组件以获得类似路由 - route to different component for similar routes with react router React Router将道具传递给渲染的组件 <Link /> ? - React Router pass props to component rendered by <Link />? 在路由内反应路由器嵌套路由 - React router nesting routes inside route 反应路由器<Link>和<Route>不将状态传递给组件 - React Router <Link> and <Route> not passing state to Component 使用内部分组为组件的路由的React Router Switch语句不会转到未找到的路由 - React Router Switch statement with routes grouped as component inside does not go to Not Found route React router redux链接更改路由,但不是组件 - React router redux Link changing route, but not component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM