高阶组件学习(react和vue)

React高阶组件(hooks写法)

1.新建高阶组件hoc.tsx

import React, { useState } from 'react';

export interface IHocProps {
  hocId: string;
  name?: string;
  children?: any;
}

export const HOC_Wrapper = (Component: Function, type?: string) => {
  return (props: IHocProps) => {
    // 权鉴是否登录
    const isAdmin = useState<boolean>(!!localStorage.getItem('token'));
    return isAdmin ? (
      <Component {...props} type={type}></Component>
    ) : (
      <div>请登录查看</div>
    );
  };
};

2.使用

// 高阶组件第一个参数组件
const hoc: FunctionComponent<IProps> = (props) => {
  useEffect(() => {
    console.log('props >>> ', props);
  }, []);
  return (
    <div>
      <p>这是木偶组件里的内容</p>
      {props.children}
    </div>
  );
};
// 声明高阶组件
const Hoc = HOC_Wrapper(hoc, 'GoodsList');
// 使用
<Hoc hocId="hocId" name="first_hoc">
  <div>哈哈哈</div>
</Hoc>

vue 高阶组件

import { h } from 'vue'
import NotFindPage from '@/views/404.vue'
export const withComponent = (wrapper, requestFunc) => ({
    data() {
        return {
            showText: ''
        }
    },
    mounted() {
        if (this.haveAuth()) {
            const params = this.$refs.wrapped.requestParams;
            this.request(params)
            this.$refs.wrapped.$watch('requestParams', (newResParams) => {
                this.request(newResParams)
            }, { immediate: true })
        }
    },
    components:{
        NotFindPage
    },
    methods: {
        request(params) {
            requestFunc(params).then((res) => {
                this.showText = 'request(' + res + ')';
            })
        },
        haveAuth() {
            return !!(localStorage.getItem('token'))
        }
    },
    render() {
        // 将 this.$slots 格式化为数组,因为 h 函数第三个参数是子节点,是一个数组
        const scopedSlots = Object.keys(this.$slots).map(key => this.$slots[key]())
        const args = {
            ...this.$props,
            text: this.showText,
            ref: 'wrapped',
            attrs: this.$attrs
        }
        return this.haveAuth() ? h(wrapper, args, [...scopedSlots]) : h(NotFindPage,{})
    }
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值