react 高阶组件如何写,一个高阶组件的小demo

高级组件 higherOrderComponent (HOC)

  是个纯函数,接收一个组件,返回一个组件

例子:
效果图
js部份
import React, { Component } from "react";
import "./Blackboard.less";

const defaultParams = {

}

export const Blackboard = (params = defaultParams) => (WrappedComponent) => {
  return class HOC extends Component {
    render() {
      return (
        <div className="Blackboard">
          <section className="code-box-demo">
            <WrappedComponent {...params}/>
          </section>
          <section className="code-box-meta markdown">
            <div className="code-box-title">
              <span>高阶组件用法举例</span>
            </div>
          </section>
        </div>
      )
    }
  }
}

less部份

.Blackboard{
  border: 1px solid #e9e9e9;
  border-radius: 6px;
  display: inline-block;
  width: 100%;
  position: relative;
  margin: 0 0 16px;
  transition: all .2s ease;
  &:hover {
    box-shadow: 0 0 6px rgba(0,0,0,.15);
    position: relative;
    z-index: 10;
    // background: #fff;
  }
  .code-box-demo{
    width: 100%;
    border-bottom: 1px solid #e9e9e9;
    padding: 42px 20px 50px;
  }
  .code-box-meta.markdown {
    position: relative;
    padding: 17px 16px 15px 20px;
    border-radius: 0 0 6px 6px;
    -webkit-transition: background-color .4s ease;
    transition: background-color .4s ease;
    width: 100%;
    font-size: 12px;
  }
  .markdown {
    color: #666;
    line-height: 1.8;
  }
  .code-box-title{
    position: absolute;
    top: -13px;
    padding: 1px 8px;
    margin-left: -8px;
    color: #777;
    border-radius: 6px;
    border-top-left-radius: 0;
    background: #fff;
    -webkit-transition: background-color .4s ease;
    transition: background-color .4s ease;
  }
}

使用方式

import React from "react";
import { Blackboard } from "components/Blackboard/Blackboard"; // 引入高阶组件
class YearPicker extends React.Component { constructor(props) { super(props)
this.state = { // ... }; } render() { return ( <div> // ... </div> ) } } // 组件导出之前包裹一下 export default Blackboard({})(YearPicker)

 

 

 

 

 

 

posted @ 2020-10-22 22:56  真的想不出来  阅读(642)  评论(0编辑  收藏  举报