前言:
1、react定义组件有两种方式:
1)、用class即定义类的形式,这种形式我们前面用到好多次了。
class WillMatch extends Component{
render(){
return(
<h1>
Matched
</h1>
)
}
}
2)、函数定义组件,这种方式是一中简便的定义组件的方式,适用于定义类方式中只有render
方法的简单组件。
function Square(props) {
return (
<button className="square" onClick={props.onClick}>
{props.value}
</button>
);
}
2、react写样式的三种方式:
1)、利用className,相当于css中的class。具体样式在style中定义。
class Square extends React.Component {
render () {
return (
<button className="square">
{/*TODO*/}
</button>
)
}
}
<style>
.square {
background: #fff;
border: 1px solid #999;
float: left;
font-size: 24px;
font-weight: bold;
line-height: 34px;
height: 34px;
margin-right: -1px;
margin-top: -1px;
padding: 0;
text-align: center;
width: 34px;
}
</style>
2)、定一个样式对象,其属性值为样式值,将变量在jsx中解析。
<script type="text/babel">
var myStyle = {
fontSize: 100,
color: '#ff0000'
}
ReactDOM.render(
<h1 style = {myStyle}>haha</h1>,
document.getElementById('example')
);
</script>
3)、今天我们例子中用的是另外一种,和第二种类似。
<div style={{ flex: 1 }}>
{
routes.map((item, index) => {
return (
<Route path={item.path} key={index} exact={item.exact} component={item.main} />
)
})
}
</div>
根据不用情况,读者可自行选择。
实现效果:

代码如下:
const routes = [
{
path: '/',
exact: true,
sidebar: () => <div>home!</div>,
main: () => <h2>Home</h2>
},
{
path: '/bubblegum',
sidebar: () => <div>bubblegum!</div>,
main: () => <h2>Bubblegum</h2>
},
{
path: '/shoelaces',
sidebar: () => <div>shoelaces!</div>,
main: () => <h2>shoelaces</h2>
}
]
class App extends Component{
render() {
return(
<Router>
<div style={{ display: 'flex' }}>
<div style={{ width: '200px', backgroundColor: '#cccccc' }}>
<ul style={{listStyleType: 'none',padding: 0}}>
<li><Link to='/'>Home</Link></li>
<li><Link to='/bubblegum'>Bubblegum</Link></li>
<li><Link to='/shoelaces'>Shoelaces</Link></li>
</ul>
{
routes.map((item, index) => {
return (
<Route path={item.path} key={index} exact={item.exact} component={item.sidebar} />
)
})
}
</div>
<div style={{ flex: 1 }}>
{
routes.map((item, index) => {
return (
<Route path={item.path} key={index} exact={item.exact} component={item.main} />
)
})
}
</div>
</div>
</Router>
)
}
}
Route对应的组件便是用函数定义的方式定义的。
倘若你还不理解请参考我的github上的这个示例:https://github.com/guoqin721/react-router-dom8