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;
}
}
至此,结束。
本文深入探讨了React组件的三种创建方式:React.createClass、ES6 classes及无状态函数,对比了它们的特点,并介绍了如何通过shouldComponentUpdate和Immutable.is进行组件优化。
893

被折叠的 条评论
为什么被折叠?



