React高级教程之高阶组件

一、高阶函数基本概念:

  • 函数可以作为参数传递;

  • 函数可以作为返回值输出;

二、高阶函数基本概念:

  • 高阶组件就是接受一个组件作为参数,返回一个新组件的函数;

  • 高阶组件是一个函数,并不是组件;

三、如何使用高阶组件:

  • 方法调用 例如: highOrderComponent(WrappedComponent);

  • @ highOrderComponent 装饰器模式

四、高阶组件应用:

  • 推荐 代理方式的高阶组件;(继承上下文来自React.Component)

  • 继承方式的高阶组件;(继承上下文来自包裹组件)

五、示例:

/* 代理方式高阶组件 */
// B.js
import React, { Component } from 'react';
import A from './A';
class B extends Component {
return (
 <div>我是组件B</div>
 )
}
export default A(B);
// A.js
const A = function (Component) {
 return (
     <div>
         我是组件A,我包裹了B
         <Component />
     </div>
     )
 }
/* 继承方式高阶组件 */
// B.js
import React, { Component } from 'react';
import A from './A';
class B extends Component {
     return (
         <div>我是组件B</div>
     )
}
export default A(B);

// A.js
const A = function (OtherComponent) {
     return class B extends OtherComponent {
         return (
             <div>我是组件B</div>
         )
     }
}
posted @ 2020-01-19 16:05  JockerM  阅读(423)  评论(0)    收藏  举报