使用react-router-dom制作一个单页开发demo
项目结构如下
我们来看index.js入口文件
import React from 'react';
import ReactDOM from 'react-dom';
import Router from './page/2019062502/main'
ReactDOM.render(
<Router/>,
document.getElementById('root')
);
然后是demo文件中的路由文件main.js
import React from 'react';
import {BrowserRouter as Router,Route,Link} from 'react-router-dom';
import Detail from './detail'
import New from './new'
export default class About extends React.Component{
render(){
return(
<Router>
<Route exact path="/" component={New}></Route>
<Route exact path="/detail:id" component={Detail}></Route>
</Router>
)
}
}
然后是demo文件中的new组件(new.js)
import React from 'react';
import {BrowserRouter as Router,Route,Link} from 'react-router-dom';
import spiderMan from '../../image/spiderMan.jpg'
import man from '../../image/captainAmerica.jpg'
export default class About extends React.Component{
render(){
return(
<div>
<ul>
<li>
<p>
<img src={spiderMan} />
</p>
<Link to='/detail0'>Detail</Link>
</li>
<li>
<p>
<img src={man} />
</p>
<Link to='/detail1'>Detail</Link>
</li>
</ul>
</div>
)
}
}
再然后是 detail组件
import React from 'react';
import spiderMan from '../../image/spiderMan.jpg'
import man from '../../image/captainAmerica.jpg'
import './detail.css'
export default class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
arr: [{
name:require('../../image/spiderMan.jpg'),
code: 1,
hero: 'Spider man1',
realName: 'Peter Parker1',
detail: 'Spider man is an American comic hero in rare and Superman, Batman, the eponymous hero of justice, was originally an ordinary college student Peter Parker'
}, {
name:require('../../image/captainAmerica.jpg'),
code: 2,
hero: 'Spider man2',
realName: 'Peter Parker2',
detail: 'Spider man is an American comic hero in rare and Superman, Batman, the eponymous hero of justice, was originally an ordinary college student Peter Parker'
}]
}
}
render() {
return (
<div className='hero'>
<div className='heroImg'><img src={this.state.arr[this.props.match.params.id].name} /></div>
<table>
<tbody>
<tr>
<td>code</td>
<td>{this.state.arr[this.props.match.params.id].code}</td>
</tr>
<tr>
<td>hero</td>
<td>{this.state.arr[this.props.match.params.id].hero}</td>
</tr>
<tr>
<td>realName</td>
<td>{this.state.arr[this.props.match.params.id].realName}</td>
</tr>
<tr>
<td>detail</td>
<td>{this.state.arr[this.props.match.params.id].detail}</td>
</tr></tbody>
</table>
</div>
)
}
}
以及detail组件对应样式detail.css
body{
margin:0;
padding: 8% 16%;
}
.hero{
display: flex;
justify-content: space-between;
align-items: center;
}
.heroImg{
flex: 1;
}
因为图片在本地,所以使用时请修改图片路径
最终效果如下
菜鸟一枚,希望大神指点