好吧我终于想通了 - 也许是不正确的/完美的方式,但它似乎工作。我将在这里编写代码,说明如何构建路由和组件。请记住,这是使用反应路由器v4,事情有点不同于以前的版本。
//Router file - index.js
//import React, BrowserRouter, React Dom, Header and Components A, B and C parent
//Create Root component, add BrowserRouter and add a subpath for browserRouter - needed for the nested routes
//Root component renders inside HTML element with an ID of main
//Have a Match for '/' (it will actually be to "/subpath")- then it renders Parent of ABC
import React from 'react';
import { render } from 'react-dom';//instead of importing ALL react dom we just import the render
//React Router V4 uses Match and Miss - if something Matches a path it will render the assigned component and you use Miss for a 404/not found page
import { BrowserRouter, Match, Miss } from 'react-router';
import Header from './components/Header';
import ComponentABCParent from './components/ComponentABCParent';
const Root =() => {
return (
<BrowserRouter basename="/subpathHere">
<div>
<div id="header">
<Header />
</div>
<div className="app-content">
<Match pattern="/" component={ComponentABCParent}/>
<Miss component={NotFound} />
</div>
</div>
</BrowserRouter>
)
}
render(<Root/>, document.getElementById('main'));
//Parent of A, B and C with nested route
//Create parent component - place inside ComponentA and two Match's
//One Match for Component B which is rendered immediately
//Second Match for ComponentC
import React from 'react';
import {Link, Match, Miss} from 'react-router';
import OracleCircle from './ComponentA';
import Intro from './ComponentB';
import StepOne from './ComponentC';
const ComponentABCParent = ({ pathname }) => {
return (
<div>
<ComponentA />
<Match exactly pattern={`${pathname}`} component={ComponentB} />
<Match pattern={`${pathname}component-c`} component={ComponentC}/>
</div>
);
}
export default ComponentABCParent;
//Component B - ComponentB.js
//Inside ComponentB I have a Link that points to ComponentC
import React from 'react';
import {Link} from 'react-router';
const ComponentB = ({pathname}) => {
return (
<div>
<h1>"Stack Overflow is not a tutorial website"</h1>
<Link to={`${pathname}component-c`}>Go to C</Link>
</div>
);
}
export default ComponentB;
//Component C - ComponentC.js
//Render ComponentC with funny answer
import React from 'react';
import {Link} from 'react-router';
const ComponentA = ({pathname}) => {
return (
<div>
<h1>"Your Momma is a tutorial website"</h1>
</div>
);
}
export default ComponentA;
希望这有助于
Stack Overflow是不是教程的网站。你试过什么了?什么没有用? –
将主要内容区域想象成一个'Parent'组件,如果url匹配'step1',它为'ComponentC'渲染'ComponentB','step2'等等...... – xiaofan2406
“点击'Next'也会交换'组件A'和'组件C'...“在这里是”A“,还是你的意思是”B“? –