最近在看React的时候被各种ES6的问题所迷惑,官网推荐用ES6的语法,然而网上搜索到的各种教程和例子很多都是ES5的,傻傻分不清呀。于是查找并整理了下ES5和ES6在React上面的写法。
引用
在ES5中,如果使用CommonJS标准,通过require来引入React包
// ES5
var React = require('react');
var MyComponent = require('./MyComponent');复制代码
在ES6中,import写法更加标准
import React from 'react'
import MyComponent from './MyComponent'复制代码
导出单个类
在ES5中,要导出一个类给别的模块用,一般通过module.exports来导出
// ES5
var MyComponent = React.createClass({
...
})
module.exports = MyComponent;复制代码
在ES6中,通常用export default来实现相同的功能:
// ES6
export default class MyComponent extends Component{
...
}复制代码
定义组件
在ES5中,通常通过React.createClass来定义一个组件:
// ES5
var Photo = React.createClass({
render: function() {
return (
<Image source={this.props.source} />
);
},
})复制代码
在ES6中,我们通过定义一个继承自React.Component的class来定义一个组件类
// ES6
class Photo extends React.Compoment {
constructor(props) {
super(props);
} // 这儿是一定不能有逗号的,如果有的话会报错
render() {
return (
<Image source={this.props.source} />
)
}
}复制代码
需要注意的是:constructor方法是类的默认方法,在生成对象时就会自动的调用该方法。一个类必须有constructor方法。如果没有显式的定义,一个空的constructor就会被默认添加。constructor方法中出现了super关键字,它在这里表示父类的构造函数,用来新建父类的this对象。子类必须在constructor方法中调用super方法,否则新建实例时会报错,因为子类没有自己的this对象。
初始化state
// ES5
var Video = React.createClass({
getInitialState: function() {
return {
loopsRemaining: this.props.maxLoops
}
}
})复制代码
// ES6
class Video extends React.Component {
// 在构造函数中初始化
constructor(props) {
super(props);
this.state = {
loopsRemaining: this.props.maxLoops
};
}
}复制代码
把方法作为回调函数提供
// ES5
var PostInfo = React.createClass({
handleclick: function(e) {
this.setState({ isToggleOn: true });
},
render: function() {
return (
<button onClick={this.handleclick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
)
}
})复制代码
// ES6
class PostInfo extends React.Component{
constructor(props) {
super(props);
// 设置初始值
this.state = { isToggleOn: true };
// ES6中函数必须手动绑定
this.handleclick = this.handleclick.bind(this);
}
handleclick(event) {
// 大括号被解释为代码块,所以如果箭头函数直接返回一个对象,必须在对象外面加上括号,否则会报错
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<div className='first'>
<button onClick={this.handleclick}>
{this.state.isToggleOn ? 'ON' : 'OFF'} {testData}
</button>
</div>
);
}
}复制代码
总体来说,ES5跟ES6还是有很大的差别的,有必要好好看一下的!整理主要参考这里