1. Babel 是一个普遍使用的转码器,将 es6 转成 es5 ,从而在现有的环境执行,因此无需担忧环境的问题,就能够使用es6语法
另外,Traceur也能够将将 es6 转成 es5
2. 配置文件.babelrc 或者在 package.json配置
{“presets”: [], ‘plugins’: []}
presets字段设定转码规则
{“presets”: [“es2015”, “react”, “stage-2”], plugins: []}
ps:npm install --save 与 npm install --save-dev 的区别是分别安装在dependencies (生产环境)和 devDependencie(开发环境)
其中
1> npm install默认会安装两种依赖
2> npm install packagename —dev (安装devDependencies)
3> npm install packagename (只会安装dependencies)
3. 与其余工具配合
例如:eslint静态检查代码的风格和语法
1> 安装:npm install —save-dev aslant babel-eslint
2> 根目录新建配置文件 .eslint , 加入 parser 字段
{‘parser’: ‘babel-eslint’, rules: {}}
3> package.json 中加入 scripts 脚本
react on es6+
1. 使用 React.Component instead React.createClass
2. constructor 与 componentWillMount 用法相同
// The ES5 way
var EmbedModal = React.createClass({
componentWillMount: function() { … },
});
constructor 默认返回实例对象(即this),
子类必须在constructor方法调用super方法,不然新建实例时会报错,由于子类继承了父类的this对象
也就是调用了父类的构造函数,react但愿把全部props和state的定义都放在父类进行,子类中须要继承父类的构造函数来使用这些值
// The ES6+ way
class EmbedModal extends React.Component {
constructor(props) {
super(props);
// Operations usually carried out in componentWillMount go here
}
}
3. 属性的初始化
// The ES5 way
var Video = React.createClass({
getDefaultProps: function() {
return {
autoPlay: false,
maxLoops: 10,
};
},
getInitialState: function() {
return {
loopsRemaining: this.props.maxLoops,
};
},
propTypes: {
autoPlay: React.PropTypes.bool.isRequired,
maxLoops: React.PropTypes.number.isRequired,
posterFrameSrc: React.PropTypes.string.isRequired,
videoSrc: React.PropTypes.string.isRequired,
},
});
// The ES6+ way
class Video extends React.Component {
static defaultProps = {
autoPlay: false,
maxLoops: 10,
}
static propTypes = {
autoPlay: React.PropTypes.bool.isRequired,
maxLoops: React.PropTypes.number.isRequired,
posterFrameSrc: React.PropTypes.string.isRequired,
videoSrc: React.PropTypes.string.isRequired,
}
state = {
loopsRemaining: this.props.maxLoops,
}
}
4.箭头函数
5.动态属性名
对于想要访问 “变量+’Value’” 动态属性名能够使用 [`${}Value`], 例如:
class Form extends React.Component {
onChange(inputName, e) {
this.setState({
[`${inputName}Value`]: e.target.value,
});
}
}
6.传递属性
其中,this.props 含有 className 属性
1> 下面 className 为 override
<div {...this.props} className="override">
…
</div>
2> 下面 clasName 为 this.props里面的值
<div className="base" {...this.props}>
…
</div>