其他分享
首页 > 其他分享> > react 高阶组件如何写,一个高阶组件的小demo

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 {...this.props} {...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)

 

 

 

 

 

 

标签:color,demo,border,6px,background,Blackboard,组件,高阶
来源: https://www.cnblogs.com/MrZhujl/p/13861554.html