装饰器和Mixins之间的区别

Aja*_*aur 2 javascript ecmascript-6 reactjs

我是个初学者,可以做出反应,发现自己在mixin和装饰器之间感到困惑。有人可以详细说明吗?谢谢。

Ric*_*wig 5

它们都扩展和/或覆盖了React组件的方法。它们用于在组件之间共享通用功能,而扩展类将无法正常使用。

例如,PureRenderMixin,它将重写该shouldComponentUpdate方法并比较组件的属性以决定是否应执行重新渲染。

但是,不推荐使用混合包,并且不再使用React的ES6语法。您的选择是使用继承或装饰器来达到相同的结果。

这是使用装饰器的(种类)PureRenderMixin的示例。我也使用了Immutable.js。

// pure.js
import React from 'react';
import assign from 'object-assign';
import {is} from 'immutable';

/**
 * Pure Render Decorator
 * @param props
 * @returns {function()}
 */
export default (...props) => (Component) => class PureComponent extends React.Component {

    shouldComponentUpdate(nextProps) {
        if (!props.length) {
            props = Object.keys(nextProps);
        }
        for (let i = 0, l = props.length; i < l; i++) {
            if (!is(nextProps[props[i]], this.props[props[i]])) {
                return true;
            }
        }
        return false;
    }

    render() {
        return React.createElement(Component, assign({},
            this.props,
            this.state
        ));
    }
}
Run Code Online (Sandbox Code Playgroud)

装饰器的一般用法是@pure(params)params可以包含道具名称,也可以为空。在装饰器中,您将看到...props作为参数。这是params传入的地方。

Component内部函数的参数获取传入的React Component,在其上使用装饰器。

您可以在组件中使用装饰器,如下所示:

import React from 'react';
import pure from './pure.js';

@pure('myProp', 'anotherProp')
export default MyComponent extends React.Component {

    static propTypes = {
        myProp: React.PropTypes.any,
        anotherProp: React.PropTypes.any
    }

    render() {
        return <p>I only re-render, when my props changed.</p>;
    }

}
Run Code Online (Sandbox Code Playgroud)

它有什么作用?

装饰器重写shouldComponentUpdate组件的方法。每当React Component调用其shouldComponentUpdate方法时,它现在都使用装饰器中提供的方法。

装饰器本身将Component的道具与其将要接收的下一个道具进行比较。仅当道具更改时,组件才会更新。很好,因为它可以防止不必要的渲染-这对性能非常有用!

您会看到,装饰器基本上是带有参数(例如React Component)并对其进行修改以使代码可重用的函数。这需要一点时间来适应,但是这不是火箭科学。:-)

如果还有其他问题,请随时提问!