React 推荐以组件的方式去重新思考 UI 构成,将 UI 上每一个功能相对独立的模块定义成组件,然后将小的组件通过组合或者嵌套的方式构成大的组件,最终完成整体 UI 的构建。
下面是一个简单的组件化例子:
index.html
<div id='container'></div>
<script src='./src/bundle.js'></script>
index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Body from './components/body';
import Header from './components/header';
import Footer from './components/footer';
class Index extends Component {
render(){
return(
<div>
<Header/>
<Body/>
<Footer/>
</div>
)
}
}
ReactDOM.render(
<Index/>,
document.getElementById('container')
);
body.js
import React, { Component } from 'react';
export default class Body extends Component {
render(){
return(
<div>Body</div>
)
}
}
(与header.jsfooter.js相同)
webpack.config.js
var webpack = require('webpack');
var path = require('path');
module.exports = {
context: __dirname + '/src',
entry: './js/index.js',
module: {
loaders: [{
test: /\.js$/,
exclude: /(node_modules)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015']
}
}
]
},
output: {
path: __dirname + '/src/',
filename: 'bundle.js'
}
}
然后在项目目录下执行 webpack 后用浏览器打开 index.html 即可