高阶组件——让你组件变高级。

149 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第17天,点击查看活动详情 

高阶组件 首先理解高阶函数 函数作为参数返回

mdn:一个返回另外一个函数的函数被称为高阶函数。

类推至高阶组件

高阶组件是参数为组件,返回值为新组件的函数。

所以高阶组件是函数,是传递一个组件给该组件赋能后返回一个新组件

###为什么要学习高阶组件

我们用到的第三方库,遍地都是用的高阶组件,学高阶组件,学习他们的思想,为我们平时开发借鉴。 所以我们平时写自定义组件,自定义方法都可以用到

高阶组件有两种实现方式,分别是属性代理(使用的比较多)和反向继承。 可以在不修改原组件情况下,来增强组件。 通常以设计模式中装饰器模式中的形式来使用。

const EnhancedComponent = highOrderComponent(WrappedComponent); 

本篇文章主要介绍,高阶组件的应用和注意。

高阶组件会丢失所有静态函数

class Index2 extends React.Component{
    render(){
        return <div> hello,world  </div>
    }
}
Index2.say = function(){
    console.log('wow,I am say noting')
}
function HOC(Component) {
   function wrappedComponentSay () {
        Component.say();
    }
    wrappedComponentSay() // wow,I am say noting
    return class wrapComponent extends React.Component{
       cacheComponent = component //在新组建中保存实例

        render(){
            return <Component { ...this.props } { ...this.state } />
        }
    }
}
const newIndex =  HOC(Index2)
console.log(newIndex.say, '========', newIndex.cacheComponent.say()) // undefined "========" wow,I am say noting

可以看到高阶组件不能调用原组件的静态方法。

必须手动复制静态方法。


function HOC(Component) {
    class WrappedComponent extends React.Component {
        /*...*/
    }
    // 必须准确知道应该拷贝哪些方法 
    WrappedComponent.staticMethod = Component.staticMethod
    return WrappedComponent
}

高阶组件一般都以with开头。

共享页面

withrouter共享数据

connect redux中的高阶函数

antd 中的很多组件也是用的高阶组件。 组件中很常用。

form

Form.create(component)通过create高阶函数让我们组件拥有form实例,具备获取FormItem中的值,和设置值,清空值等操作

modal组件在逻辑代码中弹框

通过高阶组件 构建一个弹框modal页面。最后导出一个方法。 export default () => new WithDialog(ModalDialog) withDialog给ModalDialog增加onOk onCancel方法的实现。

如此就能在代码中实现 ModalDialog({onOk:() => {})直接弹框