React 组件的构建方法

本文深入探讨了React组件的三种创建方式:React.createClass、ES6 classes及无状态函数,对比了它们的特点,并介绍了如何通过shouldComponentUpdate和Immutable.is进行组件优化。

React 组件构建的三种方法

三种方法
React.createClass
const Button = React.createClass({
	getDefaultProps() {
		return {
			color: 'blue',
			text: 'Confirm'
		}
	},

	render() {
		<button className={`btn btn-${color}`}>
			<em>{text}</em>
		</button>
	}
});
ES6 classes
import React, { Component } from 'react';

class Button extends Components {
	constructor(props) {
		super(props);
	}

	static defaultProps = {
		color: 'blue',
		text: 'Confirm'
	}

	render() {
		const { color, text } = this.props;
		return (
			<button className={`btn btn-${color}`}>
				<em>{text}</em>
			</button>
		)
	}
}
无状态函数
function Button({ color = 'blue', text = 'Confirm' }) {
	return (
		<button className={`btn btn-${color}`}>
			<em>{text}</em>
		</button>
	)
}
组件优化
shouldComponentUpdate && Immutable.is
import React, { Component } from 'react';
import { is } from 'immutable';

class App extends Component {
  shouldComponentUpdate (nextProps, nextState) {
    const thisProps = this.props || {};
    const thisState = this.state || {};

    if(Object.keys(this.props).length !== Object.keys(nextProps).length ||
      Object.keys(this.setState).length !== Object.keys(nextState).length) {
        return true;
    }

    for(const key in nextProps) {
      if(nextProps.hasOwnProperty(key) && !is(thisProps[key], nextProps[key])) {
        return true;
      }
    }

    for(const key in nextState) {
      if(nextState.hasOwnProperty(key) && !is(thisState[key], nextState[key])) {
        return true;
      }
    }

    return false;
  }
}

至此,结束。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值