> npm install -g create-react-app
> create-react-app demo-app
> cd demo-app
> npm install react-router-dom
./index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App/App';
ReactDOM.render( , document.getElementById('root'));
./src/components/App/App.js
import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import Home from '../Home/Home';
import About from '../About/About';
import Inbox from '../Inbox/Inbox';
function App() {
return (
- Home
- About
- Inbox
);
}
export default App;
./src/components/Home/Home.js
import React, { Component } from 'react';
class Home extends Component {
render() {
return (
i am home
);
}
}
export default Home;
./src/components/About/About.js
import React, { Component } from 'react';
class About extends Component {
render() {
return (
i am about
);
}
}
export default About;
./src/components/Inbox/Inbox.js
import React, { Component } from 'react';
class Inbox extends Component {
render() {
return (
i am Inbox
);
}
}
export default Inbox;
./index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App/App';
ReactDOM.render( , document.getElementById('root'));
./src/components/App/App.js
import React , { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import About from '../About/About';
class App extends Component {
constructor() {
super();
this.state = {
lists: ['10010', '10086', '8000'],
};
}
render() {
let linkList = this.state.lists.map(item => {
return (
{item}
);
});
return (
{ linkList }
);
}
}
export default App;
注:< Route>在选择渲染About组件时,其实也传给了About组件一个 match对象
。在About中直接this.props.match即可访问。
./src/components/About/About.js
import React, { Component } from 'react';
class About extends Component {
render() {
return (
about: {this.props.match.params.tel}
);
}
}
export default About;
./index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App/App';
ReactDOM.render( , document.getElementById('root'));
./src/components/App/App.js
import React from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import Home from '../Home/Home';
import About from '../About/About';
import Inbox from '../Inbox/Inbox';
function App() {
return (
- Home
- About
- Inbox
);
}
export default App;
./src/components/About/About.js
import React, { Component } from 'react';
class About extends Component {
render() {
return (
i am about
);
}
}
export default About;
./src/components/Inbox/Inbox.js
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
class Inbox extends Component {
render() {
return (
Inbox title
- Components
- Props v. State
Please select a topic.
}/>
);
}
}
function Topic(props) {
return {props.match.params.getId}
;
}
export default Inbox;