安装所须要依赖的其它第三方开源库,项目依赖以下:javascript
"dependencies": { "babel-core": "^6.21.0", "babel-loader": "^6.2.10", "babel-preset-es2015": "^6.18.0", "babel-preset-react": "^6.16.0", "react": "^15.4.2", "react-dom": "^15.4.2" }
因为要使用到 import ,因此须要使用安装babel-preset-es2015,其它的几个库都是必须的;html
module.exports = { entry: __dirname + '/app.js', output: { path: __dirname, filename: 'bundle.js' }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel', query: { presets: ['es2015', 'react'] } } ] } }
主要就是配置相应的loader,在此只须要 es2015 和 react;java
index.htmlnode
<html> <head>HelloWorld</head> <body> <div id="helloworldDiv"></div> <script type="text/javascript" src="bundle.js"></script> </body> </html>
该网页里面只有一个 id 为 helloworldDiv 的 div,和引用的一个外部 script 文件,该 script 文件由webpack打包工具生成,而并不是手动添加;react
app.jswebpack
import React from 'react'; import {render} from 'react-dom'; import ReactDom from 'react-dom';
// ReactDom.render(<h1>Hello World</h1>, document.getElementById('helloworldDiv')); render(<h1>Hello World</h1>, document.getElementById('helloworldDiv'));
在app.js,记录了'两种'渲染方法,其实是同一种渲染方法;web
能够经过ReactDom.render,也能够直接调用render方法,须要注意的是此两种方法的区别:'ReactDom' 是直接导入的整个 'react-dom',而 'render' 则在使用 import 导入的时候,添加了 '{}' 进行修饰,{} 修饰的对象为某一个具体的已知的方法,而没有 {} 修饰的则为导入的整个 'react-dom' 即 ReactDom,也就是说 render 是ReactDom对象的一个方法;babel
经过调试发现 ReactDom 对象结构以下:app
Object {
findDOMNode
render(nextElement, container, callback)
unmountComponentAtNode
unstable_batchedUpdates
...
}
正好印证了上面的断言;dom
除了使用
render(<h1>Hello World</h1>, document.getElementById('helloworldDiv'));
这样直接渲染一段组织好的html片段以外,还能够以组件的形式来对html片段进行封装;
React 容许将代码封装成组件(component),而后像插入普通 HTML 标签同样,在网页中插入这个组件。有两种定义组件类的方法:
class HelloWorld extends React.Component { render() { return (<div>Hello World</div>); } } render(<HelloWorld />, document.getElementById('testDiv'));
经过继承 React.Component ,新建立一个组件类HelloWorld,在使用的时候,直接将该组件传递给render函数的nextElement参数;
var HelloWorld = React.createClass({ render: function() { return <h1>Hello World</h1>; } });
模板插入 <HelloWorld /> 时,会自动生成 HelloWorld 的一个实例。全部组件类都必须有本身的 render 方法,用于输出组件。
注意,组件类的第一个字母必须大写,不然会报错,好比HelloWorld不能写成helloWorld。另外,组件类render函数的返回只能包含一个顶层标签,不然也会报错。
建立组件除了上面两种方式外,还能够直接经过一个function来建立。
var React = require("react"); var MyButton = function(props) { return <div> <button onClick={props.onClick}>New Item</button> </div>; }; module.exports = MyButton; // 无状态组件定义方式
须要使用 require("react") 将 react导入!
生成bundle.js后提示: It looks like you're using a minified copy of the development build of React?...
修正方法:webpack 配置添加 webpack.DefinePlugin 插件,更改NODE_ENV
module.exports = { //... plugins:[ new webpack.DefinePlugin({ 'process.env':{ 'NODE_ENV': JSON.stringify('production') } }), ....... }) ] //... }