React.js中ES6 和 ES5写法的一些差别

1、 Modules引入和输出方式
ES5 使用 CommonJS 标准,一般使用 require() 用法引入模块:

var React = require('react');
var MyComponent = require('./MyComponent');

ES5输出模块:

module.exports = MyComponent;

ES6 + import语法引入模块:

import React from 'react';
import MyComponent from './MyComponent';

ES6 输入模块:

export default class MyComponent extends React.Component{
	
}

2、 Classes, 建立组件Component的方法
ES5 的React.createClass()用法

var Photo = React.createClass({
		render: function(){
			return (
				<div>
					<images alt={this.props.description} src={this.props.src} />
				</div>
			)
		}
	});
ReactDOM.render(<Photo />, document.getElementById('root'));

ES6 + class用法

class Photo extends React.Component{
		render(){
			return (
				<div>
					<images alt={this.props.description} src={this.props.src} />
				</div>
			)
		}
	};
ReactDOM.render(<Photo />, document.getElementById('root'));

在 ES5 我们会在 componentWillMount 生命周期定义希望在 render 前执行,且只执行一次的任务

var Photo = React.createClass({
		componentWillMount: function(){}
	})

在 ES6+ 则是定义在 constructor 中

class Photo extends React.Component{
		constructor(props){
			super(props);
			// 原本在 componentWillMount 操作的可以放在这
		}
	}

3、 Method 方法定义
ES5定义方法语法:

var Photo = React.createClass({
		handleClick: function(e){},
		render: function(){}
	});

ES6可省略掉function和逗号( ’ , ’ ):

class Photo extends React.Component{
		handleClick(e){}
		render(){}
	}

4、Property 属性初始化
ES5 语法 使用propTypes 和 getDefaultProps来定义属性(props)的预设值和类型:

var Todo = React.createClass({
		getDefaultProps: function(){
			return {
				checked: false,
				maxLength: 10,
			};
		},
		propTypes: {
			checked: React.PropTypes.bool.isRequired,
			maxLengh: React.PropTypes.number.isRequired
		}, 
		render: function(){
			return ();
		}
	})

ES6语法,使用 class 中的静态属性(static properties)来定义:

class Todo extends React.Component{
		static defaultProps = {
			checked: false,
			maxLength: 10,
		};
		static propTypes = {
			checked: React.PropTypes.bool.isRequired,
			maxLengh: React.PropTypes.number.isRequired
		};
		render(){
			return ();
		}
	}

ES6的另一种写法:

   class Todo extends React.Component{
		render() {
			return(
				<View />
			)
		}
	};

	Todo.defaultProps = {
		checked: false,
		maxLength: 10,
	};

	Todo.propTypes = {
		checked: React.PropTypes.bool.isRequired,
		maxLengh: React.PropTypes.number.isRequired
	};

5、 State 状态
ES5 语法 使用 getInitialState 去初始化 state:

var Todo = React.createClass({
		getInitialState: function(){
			return {
				maxLength: this.props.maxLength
			}
		}
	})

在 ES6+ 中初始化 state 有两种写法,一种如下:

class Todo extends React.Component{
		state = {
			maxLength: this.props.maxLength,
		}
	}

另一种写在constructor中(建议用这种,方便做一些运算):

class Todo extends React.Component{
		constructor(props){
			super(props);
			this.state = {
				maxLength: this.props.maxLength,
			}
		}
	}

6、 Arrow functions 箭头函数
ES5语法,在 React.createClass() 下,预设帮你绑定好 method 的 this,你无须自行绑定:

var TodoBtn = React.createClass({
	    handleButtonClick: function(e) {
	        // 此 this 指到 component 的实例(instance),而非 button
	        this.setState({showOptionsModal: true});
	    },
	    render: function(){
	        return (
	            <div>
	                <Button onClick={this.handleButtonClick}>{this.props.label}</Button>
	            </div>
	        )
	    },
	});

ES6+ 推荐使用 bind 绑定 this 或使用 Arrow functions(它会绑定当前 scope 的 this context)两种方式:

class TodoBtn extends React.Component{
	    handleButtonClick(e){
	        // 确认绑定 this 指到 component instance
	        this.setState({toggle: true});
	    }
	    render(){
	        // 可以用 this.handleButtonClick.bind(this) 手动绑定或是 Arrow functions () => {} 用法
	        return (
	            <div>
	                <Button onClick={this.handleButtonClick.bind(this)} onClick={(e)=> {this.handleButtonClick(e)} }>{this.props.label}</Button>
	            </div>
	        )
	    },
	};

无论是 bind 或是 Arrow functions,每次执行回传都是指到一个新的函数,若需要再调用到这个函数,要先把它存起来:

class TodoBtn extends React.Component{
		constructor(props){
			super(props);
			this.handleButtonClick = this.handleButtonClick.bind(this);
		}
		componentWillMount(){
			Btn.addEventListener('click', this.handleButtonClick);
		}
	    componentDidmount(){
	        Btn.removeEventListener('click', this.handleButtonClick);
	    }
	};

7、动态属性名和模板字符串
ES5 我们要动态设定属性名,往往需要多写几行代码才能达到目标:

var Todo = React.createClass({
		onChange: function(inputName, e){
			var stateToSet = {};
			stateToSet[inputName + 'Value'] = e.tartet.value;
			this.setState(stateToSet);
		}
	})

ES6+写法相对简单:

class Todo extends React.Component{
		onChange(inputName, e) {
			this.setState({
				[`${inputName}Value`]: e.target.value,
			})
		}
	}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值