简述React 中的高阶组件运用了什么设计模式 ?

在 React 中,高阶组件(Higher-Order Components,HOC)使用了装饰器(Decorator)设计模式。

装饰器模式允许我们在不修改其原始定义的情况下,动态地给一个对象添加新的行为或者职责。在 React 中,高阶组件就是一个接收一个组件并返回新组件的函数。

function withSubscription(WrappedComponent, selectData) {
    // ...并返回另一个新的组件...
    return class extends React.Component {
        constructor(props) {
            super(props);
            this.handleChange = this.handleChange.bind(this);
            this.state = {
                data: selectData(DataSource, props)
            };
        }

        componentDidMount() {
            // ...负责订阅相关的操作...
        }

        componentWillUnmount() {
            // ...并取消订阅...
        }

        handleChange() {
            this.setState({
                data: selectData(DataSource, this.props)
            });
        }

        render() {
            // ... 并使用新数据渲染被包装的组件!
            // 请注意,我们可能还会传递其他属性
            return <WrappedComponent data={this.state.data} {...this.props} />;

发表评论

后才能评论